我想通过以下模型中的 bar 获取与单个 foo 关联的 Bar 记录,
Foo <-> Bar <-> Baz
.
class Foo < ActiveRecord::Base
has_many :foo_bar_assocs
has_many :bars, through: :foo_bar_assocs
end
class Bar < ActiveRecord::Base
has_many :bar_baz_assocs
has_many :bazs, through: :bar_baz_assocs
attr_readonly :name
end
class Baz < ActiveRecord::Base
end
class FooBarAssoc < ActiveRecord::Base
belongs_to :foo
belongs_to :bar
end
class BarBazAssoc < ActiveRecord::Base
belongs_to :bar
belongs_to :baz
end
天真的实现:
foo = Foo.find(id)
baz_of_foo = foo.bars.where(name: params[:name]).map{|b| b.bazs}.flatten.uniq
此代码生成错误查询,它执行了很多次。我想要的是如下内容:
baz_of_foo = foo.something_good_query(bar_name: params[:name])
另外,我想获取像 ActiveRecord::Relation 这样的对象,以便优化生成的 SQL 查询。
baz_of_foo.each{ ... } # SELECT DISTINCT baz.* FROM ...
baz_of_foo.count # SELECT COUNT(DISTINCT baz.*) FROM ...
baz_of_foo.exists? # SELECT baz.* FROM ... TAKE 1