通过遍历 rails 中的多个表进行搜索

Search by traversing Multiple Tables in rails

在员工索引页面中,我有列 'Region Name',其中有一个搜索字段。

现在我需要从 'Employee' table 搜索列 - 'Region Name',遍历到 'Region' table

Employee -> Company -> Organization -> Region

员工 table 拥有公司的外键 (company_id)

公司 table 具有组织外键 (organization_id)

组织 table 具有区域外键 (region_id)

区域 table 有列 'region_name'

这些是我的模型

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

class Company < ActiveRecord::Base
    belongs_to :organization
    has_many :employee
end

class Organization < ActiveRecord::Base
    belongs_to :region
    has_many :company
    has_many :employees, through: :companies
end

class Region < ActiveRecord::Base
    has_many :companies
    has_many :employees, through: :companies
end

如何搜索遍历 3 tables 和 显示该地区员工索引页的员工列表?

注:数据库-Postgresql

你可以试试这个:

Employee.joins(company: {organization: :region}).where(regions: {region_name: 'Your Region Name'})