Reputation: 555
I would like to write a Rails query using Postgresql 'LIKE'. I want to be able to search a column on the current table as well as an association table.
I can search the current table like this:
User.where("description LIKE ?", "%happy%")
I can search associations like this:
User.joins(:products).where("products.description LIKE ?", "%happy%")
How do I combine these 2 queries into one? I want to return all users whose description contains "happy" and/or has a product whose description contains "happy".
Upvotes: 1
Views: 1402
Reputation: 2952
Utilizing the squeel gem:
def self.any_description_like(criteria)
User.includes(:products).where{
(users.description =~ "%#{criteria}%") |
(products.description =~ "%#{criteria}%")
}
end
Upvotes: 0
Reputation: 136
And version
User.joins(:products).where("users.description LIKE ? AND products.description LIKE ?", "%happy%", "%happy%")
Or version
User.joins(:products).where("users.description LIKE ? OR products.description LIKE ?", "%happy%", "%happy%")
Upvotes: 4