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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With