rails创建双向关系before_create

时间:2014-11-04 23:09:40

标签: ruby-on-rails

我建立了我的关系:

  # 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

这似乎是一个常见的用例。我如何获得互惠关系?

1 个答案:

答案 0 :(得分: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不必努力理解两个关联之间的反比关系,这似乎是关键。