每个用户都有很多SaleItems
和多个NeededItems
。我想查询User 1的SaleItem名称,看看它们中是否有任何一个名称与User 2的NeededItems相似(" name"是唯一的属性)
@needed_item_of_user2 = NeededItem.where("user_id = ?", 2).first
# "Pikachu Pokemon card"
@sale_items_of_user1 = SaleItem.where("user_id = ?", 1)
# "Baseball cards", "Water Heater", "Pikachu doll", "Squirtle Pokemon card"
@matching_sale_items = @sale_items_of_user1.some_method_querying_the_names.@needed_item_of_user2.name
# It should output either "Squirtle Pokemon card" (high accuracy) or
# all except "Water Heater" (low accuracy)
我应该使用什么方法来获得@matching_sale_items?
我试过了:
@matching_sale_items = @sale_items_of_user1.select do |sale|
sale["name"] == @needed_item_of_user2.name
end
基于How do I search within an array of hashes by hash values in ruby?
和
@matching_sale_items = @sale_items_of_user1.map do |a|
a.name.downcase
end.grep(/#{@needed_item_of_user2.name.downcase[0,4]}/)
# outputs strings
将来,我想使用该方法在SaleItems表中查询与NeedItems表的匹配。
答案 0 :(得分:1)
您可以尝试这样做:
user1 = User.find 1
user2 = User.find 2
needed_items_names = user2.needed_items.pluck(:name)
matched_items = user1.sale_items.where(name: needed_items_names)
要阅读的文档: