Tôi có các lớp:Làm thế nào để db: hạt giống một mô hình và tất cả các mô hình lồng nhau của nó?
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
Tôi đang cố gắng để chèn một bản ghi vào tất cả 3 bảng như thế này:
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'
}
}
}])
Một hồ sơ được đưa vào users
bảng, nhưng không vào user_profiles
hoặc contacts
bảng. Không có lỗi nào xảy ra.
Cách thích hợp để thực hiện việc như vậy là gì?
SOLVED (nhờ @Austin L. cho liên kết)
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])
Có tất cả đã được thiết lập (tôi đã có lượt xem và tất cả đều hoạt động tốt). Nhưng tại sao nó thất bại trong db: hạt giống là vấn đề – Zabba
bạn đã loại bỏ 'accept_nested_attributes' khỏi các mô hình của bạn khi đăng ở đây? –
Có, tôi chỉ đăng ý chính của các mô hình. Tôi sẽ thêm tất cả các chi tiết. Xin lỗi :) – Zabba