Ruby on rails 在RubyonRails中如何在一个循环中遍历2个模型?
我正在使用MailKick gem,我正在向id为1到1000的用户发送电子邮件,这些用户没有选择接收电子邮件 所以我有Ruby on rails 在RubyonRails中如何在一个循环中遍历2个模型?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在使用MailKick gem,我正在向id为1到1000的用户发送电子邮件,这些用户没有选择接收电子邮件 所以我有 @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, u
@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.
但我不知道如何过滤掉那些选择退出的用户 您应该能够使用
@users = User.where.not(
id: Mailkick.opt_outs.where(active: true).pluck(:user_id)
).where("id <= 1000")
@users=User.where.not(
id:Mailkick.opt_-out.where(活动:true).pull(:user_-id)
).where(“id您可以在一个命令中执行此操作:
@users_who_have_not_opted_out = User.where(id: 1..1000)
.where.not( id: MailKick.op_outs.where(active: true).pluck(:user_id) )
第一个where
函数获取1到1000之间的所有id。第二个where.not
语句返回所有不在opt_-out列表中的id。pull(:user_-id)
将mailkit.opt_-out.where(active:true)
关联转换为用户id的数组。
然后,您可以运行:
@users_who_have_not_opted_out do |user|
# Here you would execute your send email command on user
end
如图所示,您应该将mailchick\u user
添加到您的模型中:
class User < ActiveRecord::Base
mailkick_user
end
您可以获得所有未被选中的用户ID
@opt_out_users = Mailkick.opt_outs.where(active: true,:user_id=>{'$gte'=>1,'$lte'=>1000}).map(&:user_id);
上面的语句将返回数组中的用户ID。
接下来,您可以使用这些ID搜索用户对象
@user = User.where(:id=>{'$in'=> @opt_out_users});
并循环遍历每个用户
@user.each do |user|
#code for sending mails
end
我不明白。选择退出是否与一个单独的模式相关?
@user = User.where(:id=>{'$in'=> @opt_out_users});
@user.each do |user|
#code for sending mails
end