I have model like this:
scope :search_posts, lambda { |query|
mega_posts.where( "title LIKE ? OR category_id LIKE ? OR author_id LIKE ?",
"%#{query}%",
"%#{query}%",
"%#{query}%"
)
}
Every post has one category and one author. So, I want to have possibility to find my posts by category name or author name in my query (not by id). How can I do it? Thanks.
The most basic answer would be to do a join. If you've set up your associations properly, this should Just Work:
mega_posts.joins(:category).where("posts.title LIKE :query OR categories.name LIKE :query", :query => query)
Edit: In case of multiple associated models. You can do multiple joins:
mega_posts.joins(:category, :author).where('posts.title LIKE :query OR categories.name LIKE :query OR authors.name LIKE :query', :query => query)
It's even possible to nest joins:
Category.joins(:posts => [:author])
Or to write out the joins yourself, in case their more complex than Rails readily supports:
Post.joins('left join categories as c on c.id = posts.category_id').where('c.name = ?', 'foo')
Alternatively, if you're getting into really complex searches, you may want to look into a searching engine, like Sphinx or SOLR.