开发者

implementing simple search on an objects association or an any arbitrary collection in rails

开发者 https://www.devze.com 2023-03-25 20:20 出处:网络
I have a Technique model belonging to a User with a :has_many children :through TechniqueRelationship association which relates a technique object to another technique object:

I have a Technique model belonging to a User with a :has_many children :through TechniqueRelationship association which relates a technique object to another technique object:

class User < ActiveRecord::Base
    has_many开发者_如何学Go :techniques

class Technique < ActiveRecord::Base
    belongs_to :user
    has_many :technique_relationships, :foreign_key => "parent_id"
    has_many :children, :through => :techniuqe_relationships, :source => :child

In my Technique model I have a method for determining which of a given user's techniques are eligible to be that technique object's children:

def possible_children(user)
    user.techniques - (self.children + [self])
end

All this does is take a given user's techniques and removes those techniques which are already children as well as the technique object itself and then returns the collection.

I display this collection in a view and also offer a simple search form to let the user try to find which of the techniques he/she would like to add as a child.

I would like to be able to search both the :name and :description fields of the techniques in the collection above, with multiple search terms via the OR operator, ie if the user enters "armbar" and "triangle" the query should return techniques with either "armbar" or "triangle" occurring in the name, or the description.

What would be the most efficient SQL query to accomplish this? Is there a less efficient, but easier "rails way" to do this?

Please let me know if you need any more info or clarification. Thank you for your help.


For things like these I'd look into using https://github.com/ernie/meta_search and https://github.com/ernie/meta_where

If using Rails2 https://github.com/binarylogic/searchlogic will do the job just as well.

0

精彩评论

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