使用嵌套属性创建对象
问题描述:
我需要创建一个表单,它将创建另外两个对象作为属性的对象,但这些对象应该可以从包含这些对象模板的下拉列表中获得。使用嵌套属性创建对象
class User < ActiveRecord::Base
accepts_nested_attributes_for :adresses, :profiles
end
class Address < ActiveRecord::Base
attr_accessible :city, :country
belongs_to :user
end
class Profile < ActiveRecord::Base
attr_accessible :nickname, :password
belongs_to :user
end
棘手的部分可能是,该用户没有列“ADDRESS_ID”或“profiles_id”,一切都应该去个人资料和地址,这是在同一时刻为用户创建(它们具有相同的属性作为其模板) 我真的可以使用一些帮助,不要expext全码解决方案,但一些线索将是很好
答
试试这个设置:
class User < ActiveRecord::Base
has_one :address
has_one :profile
accepts_nested_attributes_for :address, :profile
attr_accessible :adress_attributes, :profile_attributes
end
class Address < ActiveRecord::Base
attr_accessible :city, :country
belongs_to :user
end
class Profile < ActiveRecord::Base
attr_accessible :nickname, :password
belongs_to :user
end
见doc