开发者

Do has_many :through associations work for models that only exist in memory?

开发者 https://www.devze.com 2023-01-18 05:08 出处:网络
for class A < ActiveRecord::Base has_many :bs has_many :cs, :through => :bs end class B < ActiveRecord::Base

for

class A < ActiveRecord::Base
  has_many :bs
  has_many :cs, :through => :bs
end

class B < ActiveRecord::Base
  belongs_to :a
  belongs_to :c
end

class C < ActiveRecord::Base
  has_many :bs
end

If i bring up a rails console, and do

a = A.new
b = a.bs.build
b.c = C.new

Then i get

a开发者_StackOverflow.cs => []

but

a.bs[0].c => c

If a is saved, then it all works. Is this expected? why doesn't the through association work when the models only exist in memory? thanks


I guess that object a has no reference to object c created. Normally it would run a query, but it won't since it is not saved to db. I think that it is created for db relations and it just doesn't check references to in-memory objects.

You can also try this:

a = A.new
a.cs.build
a.bs
=> []

but

a.cs
=> [created c object]


Here's how I worked around it:

class A < ActiveRecord::Base
  has_many :bs

  def cs
    bs.map &:c
  end

end

You might lose something. For example, cs is now read-only so you can't assign to it or build or create on it. That's fine in my particular case because I will always mutate bs only, which is maybe a better practice. Also many-to-many objects like B will normally have some attributes that you want to set.

By the way, if C is joined to B by has_many instead of belongs_to change the above code to use flat_map instead of map.

0

精彩评论

暂无评论...
验证码 换一张
取 消