2010-12-11 48 views
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 => '[email protected]', 
    :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 => '[email protected]', 
    :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]) 

回答

3

您的用戶模型需要設置通過accepts_nested_attributes

接受嵌套的屬性中查看信息的Rails文檔和示例:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

編輯:你也可以考慮使用has_one :contact, :through => :user_profile這將允許你訪問c這樣連接:@contact = User.first.contact

編輯2: rails c玩耍後,我能找到的最好的解決辦法是這樣的:

@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:見一個更好的解決這個問題。

+0

是的,它是所有設置(我已經有了意見,他們都工作正常)。但爲什麼它在db中失敗:種子是問題 – Zabba 2010-12-11 23:56:29

+0

當你在這裏發佈時,是否從模型中刪除了'accep_nested_attributes'? – 2010-12-11 23:57:35

+0

是的,我只發佈了模型的要點。我會添加所有的細節。道歉:) – Zabba 2010-12-12 00:00:46