开发者

How do I extract the tags that are NOT in the db?

开发者 https://www.devze.com 2023-03-26 19:12 出处:网络
The Ruby and C tags exist in the db. Tag.where(:name => [\"Ruby\", \"C\", \"foo\", \"bar\"]).map(&:name)

The Ruby and C tags exist in the db.

Tag.where(:name => ["Ruby", "C", "foo", "bar"]).map(&:name) 

Returns: ["Ruby", "C"].

How do I return the tags that aren't in the db. So the opposite. i.e. ["foo", "bar"]

Looking for开发者_运维百科 an elegant Ruby one liner solution. If possible.


search_tags = ["Ruby", "C", "foo", "bar"]
not_found = search_tags - Tag.where(:name => search_tags).map(&:name)

Just a quick answer with mostly copy/pasting what you already had, adjust as needed.


I think the following would do that in one line:

["Ruby", "C", "foo", "bar"].reject { |name| Tag.where(:name => name) }

But it's not fast, because it will take 4 queries.

0

精彩评论

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

关注公众号