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.

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pluck. I found this one to search the array for nonexact matches stackoverflow.com/questions/2220423/… @matched_items = user1.sale_items.where("LOWER(name) ILIKE ?", "%#{@needed_item_of_user2.name.downcase[0,5]}%")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.