如何在轨道上的ruby循环中浏览2个模型?

时间:2017-10-26 15:12:42

标签: 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, user_id and active as fields. 

现在我可以运行代码

@users.each do |user|

//Code to send emails to each user

end

但是我无法弄清楚如何过滤掉那些选择退出的用户。

4 个答案:

答案 0 :(得分:4)

作为documentation says,您应该将mailkick_user添加到您的模型中:

class User < ActiveRecord::Base
  mailkick_user
end

然后范围.not_opted_out将为您提供:

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

答案 1 :(得分:2)

你应该可以使用

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

条款.where('id >= 1')是多余的。

答案 2 :(得分:1)

您可以在一个命令中执行此操作:

@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。 pluck(:user_id)MailKick.opt_outs.where(active:true)关联转换为user_ids

数组

然后您可以运行:

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

答案 3 :(得分:0)

您可以获得所有未选择退出的用户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