0

Each User has many SaleItems and many NeededItems. I want to query User 1's SaleItem names to see if any of them has a similar name to User 2's NeededItems ("name" is the only attribute)

@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)

What method should I use to get an accurate match for @matching_sale_items?

I've tried:

@matching_sale_items = @sale_items_of_user1.select do |sale| 
  sale["name"] == @needed_item_of_user2.name
end 

based on How do I search within an array of hashes by hash values in ruby?

and

@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

In the future, I want to use that method to query the SaleItems Table for matches with the NeedItems Table.

Sebastian Palma
  • 29,105
  • 6
  • 30
  • 48
Jun Dalisay
  • 851
  • 1
  • 8
  • 18

1 Answers1

1

You can try to do this:

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)

Docs to read:

kolas
  • 745
  • 5
  • 15
  • Thanks for pluck. I found this one to search the array for nonexact matches https://stackoverflow.com/questions/2220423/case-insensitive-search-in-rails-model `@matched_items = user1.sale_items.where("LOWER(name) ILIKE ?", "%#{@needed_item_of_user2.name.downcase[0,5]}%")` – Jun Dalisay Oct 16 '17 at 08:59