通过遍历rails

时间:2016-07-07 14:22:03

标签: ruby-on-rails-4 search activerecord rails-activerecord advanced-search

在员工索引页面中,我有“区域名称”列,带有搜索字段。

现在我需要从'Employee'表中搜索column-'Region Name',遍历'Region'表

Employee -> Company -> Organization -> Region

员工表具有公司的外键(company_id)

公司表具有Organization(organization_id)的外键

组织表具有Region(region_id)的外键

区域表的列为'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个表格和 在该地区的员工的索引页面中显示员工列表?

注意:database-Postgresql

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

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