I have a tagging system in rails using postgres' array data type. I'm trying to write a scope that will return any posts that include a tag. So far I have this scope working:
scope :with_tag, ->(tag) { where("tags @> ARRAY[?]", tag) }
I want to extend this scope so that I can query on multiple tags at the same time, ideally something like:
Post.with_tags(['some', 'tags', 'to', 'query'])
Which would return any Post that have one of those tags. I've thought about making a class method to handle iterating over the input array:
def self.with_tags(args)
# start with empty activerecord relation
# want to output AR relation
results = Post.none
args.each do |tag|
results = results.concat(Post.with_tag(tag))
end
results.flatten
end
but this approach smells funny to me because it's creating a new query for each argument. It also doesn't return an ActiveRecord::Relation because of flatten, which I would really like to have as the output.
Can I accomplish what I'm after in a scope with an OR query?
tagscolumn and an array of strings in the Rubyargsvariable and you want rows where those arrays overlap?tagsthat contain any of the values inargs, they do not need to match all of theargs