Rails - 根据关联值搜索对象

Rails - Search for object based on association's value

我有两个模型 CompanyInsuredObjectCompany has_many InsuredObjects 和相反的 belongs_to。目前,我有一个功能搜索 InsuredObject(s) returns 所有包含搜索输入的对象,如下所示:

# /models/insured_objects.rb

def self.search(search)
  query = "%#{search}%"
  if search
    where("object LIKE ? OR insurance_type LIKE ? OR class_code LIKE ? OR information LIKE ?", 
        query, query, query, query)
  end
end

和:

# /controllers/insured_objects_controller.rb

def index
  @insured_objects = InsuredObject.search(params[:search])
end

每个 Company 都有一个 is_active 属性。我正在尝试寻找一种方法来搜索相同的东西,但只有 return InsuredObject(s) 他们的 Companyis_active 属性是 true.有什么想法吗?

从活跃的公司中获取 InsuredObject 的所有条目:

InsuredObject.joins(:company).where(companies: {is_active: true})

joins(:company)中,:company是协会名称(在InsuredObject中你应该有belongs_to :company

where(companies: ... 中,:companies 是模型 Company

的 table 名称