Joins across multiple tables with ActiveRecord with named scopes

孤者浪人 提交于 2020-01-14 05:12:06

问题


I love making named scopes for rails. however, I ran into somewhat of a pickle. Ive gotten pretty comfortable using named scopes for joins like so:

named_scope :foo, :joins => :bar, :conditions => "bar_attribute = 'something'"

Now pretend I have a table called baz which is contains a foreign key from the bar table. I need something like this:

named_scope :foo, :joins => (:bar => :baz), :conditions => "bar.id = baz.bar_id AND baz_attribute = 'something_else'"

How possible is this?

thanks


回答1:


You are not that far off. This should work for you:

named_scope: foo, :joins => {:bar => :baz}, :conditions => "bazes.your_attr = 'something_else'"

This assumes that the plural of baz is bazes. You don't need to specify the condition that joins bar.id to bazes.bar_id, it will be inferred from :joins.




回答2:


Maybe you can do this in combination with a has_many :through => ... relation.



来源:https://stackoverflow.com/questions/1189086/joins-across-multiple-tables-with-activerecord-with-named-scopes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!