简体   繁体   中英

How to go through 2 models in a loop in ruby on rails ?

I am using MailKick gem and I am sending emails to users from id 1 to 1000 who have not opted out to get emails.

So I have

@users = User.where('id >= 1').where('id <= 1000')
@opt_out_users = Mailkick.opt_outs.where(active: true)

User model has id, email and name as fields.
MailKick model has id, email, user_id and active as fields. 

Now I can run the code

@users.each do |user|

//Code to send emails to each user

end

but I am not able to figure out how to filter out those users who have opted out.

As documentation says , you should add mailkick_user to your model:

class User < ActiveRecord::Base
  mailkick_user
end

Then scope .not_opted_out will be avaliable for you:

User.not_opted_out.where('id <= 1000').each { |user| user.do_smth }

You should be able to use

@users = User.where.not(
  id: Mailkick.opt_outs.where(active: true).pluck(:user_id)
).where("id <= 1000")

The clause .where('id >= 1') is redundant.

You can do this in one command:

@users_who_have_not_opted_out = User.where(id: 1..1000)
  .where.not( id: MailKick.op_outs.where(active: true).pluck(:user_id) )

The first where function gets all ids between 1 and 1000. The second where.not statement returns all ids that are not in the opt_out list. The pluck(:user_id) turns the MailKick.opt_outs.where(active:true) association into an array of user_ids

You can then run:

@users_who_have_not_opted_out do |user|
  # Here you would execute your send email command on user
end

you can get all user ids who are not opted out like this,

@opt_out_users = Mailkick.opt_outs.where(active: true,:user_id=>{'$gte'=>1,'$lte'=>1000}).map(&:user_id);

The above statement will return the user ids in an array. Next you can can search user object using those ids.

@user = User.where(:id=>{'$in'=> @opt_out_users});

And loop through each user

@user.each do |user|
   #code for sending mails
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM