Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query through associations - Rails 3

I'd like to make some queries just like this:

employees = Employee.where(:group.name => 'admin')
employees = Employee.where(:company.address.city => 'Porto Alegre')

I mean, I need to access fields that are in another model via association.

Thanks in advance

like image 860
MatheusJardimB Avatar asked Mar 25 '12 04:03

MatheusJardimB


1 Answers

assuming a company can have multiple addresses (which I'm assuming because of your company.address.city namespacing, and because it makes for an interesting query example):

class Group < ActiveRecord::Base
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :group
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :employees
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :company
end

The queries you're looking for would be as follows:

Employee.
  joins(:group).
  where(:groups => { :name => 'admin' })
Employee.
  joins(:company => :addresses).
  where(:addresses => { :city => 'Porto Alegre' })

note that in the where clauses above the plural form of the association is always used. The keys in the where clauses refer to table names, not the association name.

like image 168
Patrick Klingemann Avatar answered Oct 20 '22 13:10

Patrick Klingemann