Join multiple tables with ActiveRecord with named scopes

I like to create named areas for rails. however, I came across a bit of pickle. Ive got a fairly convenient use of these areas for such associations:

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

Now, let's pretend that I have a baz table that contains the foreign key from the table. I need something like this:

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

How is this possible?

thanks

+1
source share
2 answers

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

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

This suggests that the plural of baz is bazes. You do not need to specify a condition that connects bar.id with bazes.bar_id, it will be inferred from: join.

+3
source

, has_many :through => ....

0

Source: https://habr.com/ru/post/1716068/


All Articles