通过关联查询 - Rails 3

Mat*_*imB 5 ruby-on-rails ruby-on-rails-3

我想像这样提出一些问题:

employees = Employee.where(:group.name => 'admin')
employees = Employee.where(:company.address.city => 'Porto Alegre')
Run Code Online (Sandbox Code Playgroud)

我的意思是,我需要通过关联访问另一个模型中的字段.

提前致谢

Pat*_*ann 19

假设公司可以有多个地址(我假设因为你的company.address.city命名空间,并且因为它产生了一个有趣的查询示例):

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
Run Code Online (Sandbox Code Playgroud)

您正在寻找的查询如下:

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

请注意,在上面的where子句中,始终使用复数形式的关联.where子句中的键指的是表名,而不是关联名.