AHinson AHinson - 1 month ago 8
SQL Question

Rails - Search for object based on association's value

I've got two models

Company
and
InsuredObject
.
Company
has_many
InsuredObjects
and the reverse
belongs_to
. Currently, I have a functioning search for
InsuredObject
(s) that returns all objects that contain the search input as shown below:

# /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


and:

# /controllers/insured_objects_controller.rb

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


Each
Company
has a
is_active
attribute. I'm trying to think of a way to search for the same thing but only return
InsuredObject
(s) that their
Company
's
is_active
attrutbute is
true
. Any thoughts?

Answer

Get all entries of InsuredObject from active companies:

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

In joins(:company), :company is a name of association (in InsuredObject you should have belongs_to :company)

In where(companies: ..., :companies is a table name for model Company

Comments