Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use scopes to join across multiple tables

I am new to ROR and I am trying to understand scopes. In my current implementation I am getting all the Processors and displaying it in the view.

class ProcessorsController
  def index
    @processors = Processor.all    
  end
end

I want to modify this so I can get only the processors where the user is admin. This is how my relations are set up.

class Processor
  belongs_to :feed

  #SCOPES (what I have done so far)
  scope :feed, joins(:feed)
  scope :groups, joins(:feed => :groups).join(:user).where(:admin => true)
end

class Feed < ActiveRecord::Base
  has_and_belongs_to_many :groups
end

class Group < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :groups
  scope :admin,     where(:admin     => true)
end

I was able to do this in my pry

pry(main)> Processor.find(63).feed.groups.first.user.admin?

PS: could someone provide some good resources where I could learn how to use scopes if the relationships are complex.

like image 979
yesh Avatar asked Oct 23 '13 22:10

yesh


People also ask

How to join multiple tables using left join?

When we use LEFT JOIN in order to join multiple tables, it’s important to remember that this join will include all rows from the table on the LEFT side of the JOIN. Let’s rearrange the previous query: At first, you could easily say, that this query and the previous one are the same (this is true when using INNER JOIN).

Why do I need multiple columns to join tables?

Or the tables you want to join may not have just one common column to use for joining. In situations like these, you may need to use multiple columns to join tables – e.g., the first and the last names, or the order number and the year if the order numbering restarts each year.

How to query multiple database tables at once with SQL joins?

How to Query Multiple Database Tables at Once With SQL Joins Initialize Sample Database. You should get a result stating there are 2000 rows within the customers table. Default / INNER Join. The default join used within MySQL databases is called the INNER join, and is the most common and... LEFT ...

How important is the Order of the tables in joins?

When you’re using only INNER JOINs to join multiple tables, the order of these tables in joins is not important. The only important thing is that you use appropriate join conditions after the “ON” (join using foreign keys)


1 Answers

scope :with_admin, -> { joins(:feed => { :groups => :user }).where('users.admin' => true) }

As for the resources, have you gone through the official documentation on ActiveRecord joins?

like image 191
Marcelo De Polli Avatar answered Nov 14 '22 17:11

Marcelo De Polli