Yasir
Yasir

Reputation: 909

Loop through an array in user model to find a match

I am a bit new to Rails console as a UI Engineer but, I am trying to loop through each user, and find within a specific array of products if the products array contains a couple product ids. Because the products array is no more than 20 values, the products array is a part of the user model. for ex --

users purchase products 801,808,902

a user could have a products array that contains [800,801,802,808,809...]

i want to find all users that contain either 801, 808

for those that match the set, associate a new product for all these users (a free gift)

I wanted to apply it via the production rails console as a quick script

thanks for the help in the right direction!

I tried to do the following -- User.where(:product => [801,808]) with no luck

Upvotes: 1

Views: 702

Answers (2)

monkbroc
monkbroc

Reputation: 838

If you don't have too many objects in your database and you want to run a quick one-off script in the console you can do this:

desired_product_ids = [801, 808]
User.find_each do |user|
  unless (user.product_ids & desired_product_ids).empty?
    give_gift user
  end
end

def give_gift(user)
  # your gift logic
  user.save
end

This will load all your active record User objects in memory in batches so it will take a long time if your database is large.

I would recommend using a where query like NEO-xx suggested. You can combine that with the find_each:

User.where(<your condition here>).find_each do |user|
  give_gift user
end

Upvotes: 1

ashishmohite
ashishmohite

Reputation: 1120

If you have two models as User and Product . something like this should solve your problem

product_ids = [801, 808]
User.joins(:products).where(products: {id: product_ids})

Upvotes: 1

Related Questions