5

私はこれらのクラスを持っています:

class User
  has_one :user_profile
  accepts_nested_attributes_for :user_profile
  attr_accessible :email, :password, :password_confirmation, :user_profile_attributes
end

class UserProfile
  has_one :contact, :as => :contactable
  belongs_to :user
  accepts_nested_attributes_for :contact
  attr_accessible :first_name,:last_name, :contact_attributes
end

class Contact
   belongs_to :contactable, :polymorphic => true 
   attr_accessible :street, :city, :province, :postal_code, :country, :phone
end

次のように、3つのテーブルすべてにレコードを挿入しようとしています。

consumer = User.create!(
  [{
  :email => 'consu@a.com',
  :password => 'aaaaaa',
  :password_confirmation => 'aaaaaa',
  :user_profile => {
      :first_name => 'Gina',
      :last_name => 'Davis',
      :contact => {
        :street => '221 Baker St',
        :city => 'London',
        :province => 'HK',
        :postal_code => '76252',
        :country => 'UK',
        :phone => '2346752245'
    }
  }
}])

レコードはテーブルに挿入されますが、またはテーブルには挿入されusersません。エラーも発生しません。user_profilescontacts

そのようなことをする正しい方法は何ですか?

解決済み(リンクを提供してくれた@Austin L.に感謝)

params =  { :user =>
    {
    :email => 'consu@a.com',
    :password => 'aaaaaa',
    :password_confirmation => 'aaaaaa',
    :user_profile_attributes => {
        :first_name => 'Gina',
        :last_name => 'Davis',
        :contact_attributes => {
            :street => '221 Baker St',
            :city => 'London',
            :province => 'HK',
            :postal_code => '76252',
            :country => 'UK',
            :phone => '2346752245'
          }
      }
  }
}
User.create!(params[:user])
4

1 に答える 1

3

ユーザーモデルは、を介してネストされた属性を受け入れるように設定する必要がありますaccepts_nested_attributes

詳細と例については、Railsのドキュメントを参照してください:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

編集:また、次has_one :contact, :through => :user_profileのように連絡先にアクセスできるようにする使用を検討することもできます@contact = User.first.contact

rails c編集2:私が見つけることができる最良の解決策で遊んだ後はこれです:

@c = Contact.new(#all of the information)
@up = UserProfile.new(#all of the information, :contact => @c)
User.create(#all of the info, :user_profile => @up)

編集3:より良い解決策については質問を参照してください。

于 2010-12-11T23:53:12.097 に答える