Reputation: 735
Here I have search action in model
def self.search(search)
if search
self.or({date: /#{Regexp.escape(search)}/i}})
else
scoped
end
end
It works fine now I want to add search for asset field also but I have relation
has_and_belongs_to_many :assets,:class_name => 'Asset'
"asset_ids" : [ ObjectId("5093a6996d7ab80e41000008") ]
I want to search for asset also.
self.or({date: /#{Regexp.escape(search)}/i},{asset.name: /#{Regexp.escape(search)}/i})
Now like this format I have to search asset name also. But this is wrong query. Any idea? Since asset ids is here through asset id I want to search asset name . How is it possible?
Upvotes: 0
Views: 332
Reputation: 334
Check out the mongoid_search gem by mauriciozaffari. It should give you a more complete search option. It should be able to search through relations. I am also of the understanding it splits the search that is made by whitespace so you will have a more thorough search check it out here
Hope it helps.
EDIT:
I haven't actually used this myself but as far as I can tell you will need to take the following steps:>/p?
1) install the gem in your gemfile
gem 'mongoid_search'
(unless you are using mongoid 2.x.x in which case lock the gem at 0.2.8)
2) From the model that you want to search in add
class Product
include Mongoid::Document
include Mongoid::Search
field :brand
field :name
has_many :tags
belongs_to :category
search_in :brand, :name, :tags => :name, :category => :name
end
class Tag
include Mongoid::Document
field :name
belongs_to :product
end
class Category
include Mongoid::Document
field :name
has_many :products
end
So essentially what you are saying here as far as I can tell is; I have a model Product
that has fields brand
and name
. Product
can have many Tags
and there can be many products attached to a Category
. Then you import Mongoid::Search
in the product model, define what fields you want to search in so: Product fields -> brand and name
also through the link has many
search the name
field in Tags
and search the name
field and in the Category
model I think!.
Then from here you will be able to call:
Product.full_text_search("value")
Which will search your product model on name
and brand
also
There are also a few options for full text search that you should look into from the README.md I put in the link above. I think the most relevant one would be relevant_search
which I think allows you to search through the model associations
Again I haven't used this gem yet, but this is just what I gather from the README.md
Upvotes: 1