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