chell
chell

Reputation: 7866

how to do this query in rails to get search two columns from one table and one column from another table

I have the following association:

class Resource < ActiveRecord::Base belongs_to :author

 def self.search(search)
     where('title ILIKE ? OR description ILIKE ?', "%#{search}%","%#{search}%")
 end

I need to search for the author name as in the following:

 where('title ILIKE ? OR description ILIKE ? OR author_name ILIKE ?', "%#{search}%","%#{search}%","%#{search}%" )

end

This obviously won't work as I have the author_id in the Resource table and not the author name field.

I'm a NOOB so any help appreciated

Thanks

Upvotes: 0

Views: 164

Answers (1)

RichOnRails
RichOnRails

Reputation: 194

You can use the joins method to join the authors table. See example below:

def self.search(search)
 joins(:author).where('title ILIKE ? OR description ILIKE ? OR authors.name ILIKE ?', "%#{search}%","%#{search}%","%#{search}%")
end

Upvotes: 2

Related Questions