Reputation: 20633
I have a class Post
, with the following scope:
scope :by_tag, ->(tag){ where(:desc => /##{Regexp.escape(tag)}/) }
It works very well with one tags, but I can't make it work with various tags.
For example: I cant make it give me the posts tagged with #rails AND #regexp.
With criteria union I can make it return me the posts tagged with #rails OR #regexp.
How can I get it to work? I'm using mongoid, btw.
Thanks in advance.
Just fount that is not an OR. What happens is that the second time I call by_tag, it overrides the previous. I believe that's because it's the same property.
Someone know how to fix this? Thanks
Upvotes: 2
Views: 198
Reputation: 176402
Regexp queries tend to be really slow. Instead, store an array of tags and use $in
to query the array.
With Mongoid 2.x use all_in
scope :by_tags, ->(*tags) { all_in(tags: *tags) }
With Mongoid 3 use all
merge strategy
scope :by_tags, ->(*tags) { all(tags: *tags) }
Upvotes: 1