MetaSearch::Builder#relation and you
CommentsA recurring question I have been seeing regarding MetaSearch has been the need to modify or access the relation generated by the search. That’s precisely why MetaSearch::Builder#relation exists, so I thought I’d make a quick post detailing its usage.
While MetaSearch::Builder is doing its thing, handling your search params, it’s building up an ActiveRecord::Relation that will eventually be used for your results. So, in your controller, you might have:
@search = Article.search(params[:search])
@articles = @search.all
You can instead be sure to lazy load those articles in your view by instead doing:
@search = Article.search(params[:search])
@articles = @search.relation
You can also do some fun little tricks with scopes, if you’re so inclined:
# article.rb
class Article < ActiveRecord::Base
scope :with_titles_containing_hi, search(:title_contains => 'hi').relation
scope :with_titles_containing_there, search(:title_contains => 'there').relation
end
ruby-1.9.2-p0 > Article.with_titles_containing_hi.
with_titles_containing_there.to_sql
=> "SELECT \"articles\".* FROM \"articles\"
WHERE (\"articles\".\"title\" LIKE '%hi%')
AND (\"articles\".\"title\" LIKE '%there%')"
I tend to prefer using MetaWhere for things like that but it’s a neat trick, all the same.
So, there you have it: MetaSearch::Builder#relation. Use it wisely.
comments powered by Disqus