0
我建立我的关系,双向关系:轨创建before_create
# models
class Lead < ActiveRecord::Base
has_many :practices, through: :lead_practices
accepts_nested_attributes_for :practices
end
class Practice < ActiveRecord::Base
has_many :leads, through: lead_practices
end
# leads controller
def create
@lead_profile = LeadProfile.new lead_profile_params
puts "lead practice #{@lead.practices.first}"
puts " practice lead #{@lead.practices.first.lead.first}"
end
# view:
<%= form_for @lead do |f| %>
<%= f.text_field :something %>
<%= f.fields_for :practices do |practice_builder| %>
<%= practice_builder.text_field :something_else %>
<% end %>
<% end %>
的问题是在创建行动,我可以访问通过领先的做法,但我无法通过实践获得了领先优势。这将成为一个问题时,我想通过实践来访问率先在实践中的before_create回调:
class Practice < ActiveRecord::Base
before_create :do_something
def do_something
lead.first.do_something # raises an exception because practices is nil, even though it should be populated with the relation
这似乎是一个常见的情况。我怎样才能访问互惠关系?
引发异常的代码行看起来是错误的:如果它确实是'Practice'模型的一部分,它应该是'leads.first.do_something',否? – 2014-11-05 04:05:33
是的,这是一个错字。我没有复制有问题的确切代码@ToddAgulnick – Donato 2014-11-05 15:43:03
Nit:代码仍然是错误的:s/lead/leads /。 – 2014-11-05 16:55:35