accepts_nested_attributes_for - belongs_to,has_many,fields_for

时间:2011-10-23 23:38:38

标签: ruby-on-rails activerecord

有没有办法以下面的方式使用nested_attributes_for? 基本上我想创建一个人,一辆或多辆汽车并为每辆车添加细节。这只是一个模拟,而不是一个非常现实的例子。在尝试为汽车制造细节时,我遇到了障碍,因为它尚未创建。

型号:

class Person < ActiveRecord::Base
   has_many :cars
   accepts_nested_attributes_for :car
end

class Car < ActiveRecord::Base
  belongs_to :person
  has_many :details
  accepts_nested_attributes_for :details
end

class Detail < ActiveRecord::Base
  belongs_to :car
end

形式:

form_for @person do |f|
  #fields
  f.fields_for :car do |car|
    #fields
    car.fields_for :details |detail|
      =detail.text_field :content
    end
  end
end