Search code examples
sqlruby-on-railsrubyactiverecordsql-like

Create Rails query using LIKE that searches over association tables


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".


Solution

  • 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%")