如何访问fields_for对象的关联方法?

时间:2012-12-15 23:55:42

标签: ruby-on-rails

我很难以深层嵌套的形式访问fields_for对象的关联方法。你能帮我理解我哪里出错吗?

机会模式:

class Opportunity < ActiveRecord::Base
  has_many :seedlings
  accepts_nested_attributes_for :seedlings
end

幼苗模型:

class Seedling < ActiveRecord::Base
  belongs_to :opportunity
  belongs_to :potential_building
  accepts_nested_attributes_for :potential_building
end

PotentialBuilding模型:

class PotentialBuilding < ActiveRecord::Base
  has_many :seedlings
end

我希望我能在hidden_​​field旁边写下potential_building的名字,但我显然不理解某些东西。我可以将potential_building_id写入页面,就像这样(haml):

...
= opportunity_form.fields_for :seedlings do |seedling_form|
  = seedling_form.hidden_field :potential_building_id
  = seedling_form.object.potential_building_id # => 73
....

我希望访问该协会的方法会像这样简单,我不明白为什么不这样做。

...
= opportunity_form.fields_for :seedlings do |seedling_form|
  = seedling_form.hidden_field :potential_building_id
  = seedling_form.object.potential_building.name # => undefined method `name' for nil:NilClass
...
你可以帮我理解吗?谢谢。

1 个答案:

答案 0 :(得分:0)

class Opportunity < ActiveRecord::Base
  has_many :seedlings
  accepts_nested_attributes_for :seedlings
end

http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/