简体   繁体   中英

Rails OR query with postgres array

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?

我没有运行代码,但我认为&&运算符&&您的要求:

scope :with_tags, ->(tags) { where("tags && ARRAY[?]", tags) }

This will help you.

 intersection = Post.all.map do |i|
                    i.tags & [ "Your" ,"array"]
                 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM