开发者

How can I combine record results in Rails?

开发者 https://www.devze.com 2022-12-16 19:58 出处:网络
So I have two separate queries: tagged_items = Item.tagged_with(params[:s], :on => :tags) searched_items = Item.find(:all, :conditions => [\"MATCH(title) AGAINST (? IN BOOLEAN MODE)\", \"*#{par

So I have two separate queries:

tagged_items = Item.tagged_with(params[:s], :on => :tags)
searched_items = Item.find(:all, :conditions => ["MATCH(title) AGAINST (? IN BOOLEAN MODE)", "*#{params[:s]}*"])
开发者_StackOverflow社区

The first tagged_items is using the acts_as_taggable_on plugin to find all the items tagged with XYZ.

The second, searched_items, is used to search the items table for the search term.

So, how could I combine (and avoid duplicates) the results of these two?


Check out named_scope. The second query can be converted to named_scope easily, I'm not sure about the first one, but if you can rewrite it using find, you're home.

http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html


items = (tagged_items + searched_items).unique

But it would be much better if you could fetch them with single query.


This approach...

@items = tagged_items | searched_items

...would make more sense if you're looking to use the results of these queries in a View, instead of working with an Array, and accomplishes the de-duplication as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消