0

我对 has_many through 有一个令人沮丧的问题:即在保存之前不会创建直通模型这一事实。不幸的是,我需要在保存父模型之前在这些模型上设置数据。

这是松散的设置:

class Wtf < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

class Bar < ActiveRecord::Base
  has_many :wtfs
  has_many :foos, :through => :wtfs
end


class Foo < ActiveRecord::Base
  has_many :wtfs
  has_many :bars, :through => :wtfs

  def after_initialize
    Bar.all.each do |bar|
      bars << bar
    end
  end

end

一切都很好,除了我需要在保存之前访问“wtf”:

f = Foo.new => #

f.bars => [酒吧列表]

此处为空列表

f.wtfs => []

f.保存!=> 真

现在我得到东西

f.wtfs => [东西列表]

我什至明确地创建了 wtfs 这样做:

 def after_initialize
    Bar.all.each do |bar|
      wtfs << Wtf.new( :foo => self, :bar => bar, :data_i_need_to_set => 10)
    end
  end

这会导致填充 f.wtfs,但不会填充条。当我保存和检索时,我得到了预期的 wtfs 的两倍。

有人有想法么?

4

3 回答 3

2

我认为你有Wtfs直接创建的正确想法。我认为如果您同时设置栏,结果会很好:

def after_initialize
  Bar.all.each do |bar|
    wtfs << Wtf.new(:bar => bar, :data_i_need_to_set => 10)  # Rails should auto-assign :foo => self
    bars << bar
  end
end

Rails 应该正确保存记录,因为它们是相同的对象集合。唯一的拖累可能是,如果 rails 没有智能来检查Barbar 集合中的新记录是否已经Wtf关联,它可能会创建一个。试试看。

于 2010-05-13T21:31:20.170 回答
1

You could set the method that populates bar to an after_create, like this:

class Foo < ActiveRecord::Base
  has_many :wtfs
  has_many :bars, :through => :wtfs
  after_create :associate_bars

  def associate_bars
    Bar.all.each do |bar|
      bars << bar
    end
  end
end

This would make the wtfs be already be created when this method is called.

于 2010-05-13T21:08:46.917 回答
1

您不能before_save在 Wtf 上编写一个处理程序来设置您需要设置的数据吗?如果需要,它可以同时访问 foo 和 bar。

于 2010-05-13T20:47:15.880 回答