Reputation: 4738
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.
Upvotes: 2
Views: 168
Reputation: 35
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
Upvotes: 0
Reputation: 13487
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 }
Upvotes: 4
Reputation: 6036
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
Upvotes: 1
Reputation: 2436
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.
Upvotes: 2