我想通过以下模型中的条形获得与单个foo关联的条形记录,
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
答案 0 :(得分:0)
您也应该定义反向关系,一旦完成,您应该能够做到这样的事情:
Baz.joins(:bar => :foo).where(:bar => {:name => params[:name], :foo => {:id => foo_id}})
对于复杂查询,我还建议squeel gem,它允许更紧凑的查询,也支持外连接。