您应该更深入地阅读 rubyonrails api ;)链接
class Member < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts
end
您现在可以通过属性散列设置或更新关联帖子模型的属性。
对于每个没有 id 键的散列,将实例化一条新记录,除非散列还包含评估为 true 的 _destroy 键。
params = { :member => {
:name => 'joe', :posts_attributes => [
{ :title => 'Kari, the awesome Ruby documentation browser!' },
{ :title => 'The egalitarian assumption of the modern citizen' },
{ :title => '', :_destroy => '1' } # this will be ignored
]
}}
member = Member.create(params['member'])
member.posts.length # => 2
member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
member.posts.second.title # => 'The egalitarian assumption of the modern citizen'