2014-11-04 27 views
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 

这似乎是一个常见的情况。我怎样才能访问互惠关系?

+0

引发异常的代码行看起来是错误的:如果它确实是'Practice'模型的一部分,它应该是'leads.first.do_something',否? – 2014-11-05 04:05:33

+0

是的,这是一个错字。我没有复制有问题的确切代码@ToddAgulnick – Donato 2014-11-05 15:43:03

+0

Nit:代码仍然是错误的:s/lead/leads /。 – 2014-11-05 16:55:35

回答

0

你试过has_and_belongs_to_many而不是has_many :through?那就是:

class Lead < ActiveRecord::Base 
    has_and_belongs_to_many :practices 
end 

class Practice < ActiveRecord::Base 
    has_and_belongs_to_many :leads 
end 

我不知道这是否会改善你的情况,但似乎这是值得一试,因为它写这种方式意味着ActiveRecord的没有工作,因为很难理解两个关联之间的反比关系,这在这里看起来很关键。