RubyonRails:从活动记录查询创建数组



我有一个查询,可以根据特定条件查找属性。我在查询中包括Users表,这样我就可以访问属性所有者(user_id(,并向他们发送一封关于该属性的电子邮件。

@testproperties.users.each do |property|
UserMailer.with(property: property, user: property.user).check_listing.deliver
property.update_columns(property_reminder_date: Time.now )
end

这很好,只是因为我正在循环浏览属性,如果用户有一个以上的属性,他们将收到X数量的电子邮件。我想按用户进行捆绑。

因此,如果一个用户有两个属性,我想向该用户及其多个属性发送邮件。他们将收到1封电子邮件,而不是2封。并且电子邮件视图将被馈送一系列属性。

但我不知道该怎么做。我需要循环访问用户,并将他们的属性连接到他们。

编辑:

如果我做这样的查询:

@testusers = User.joins(:properties)
.where("properties.updated_at < :date", date: 30.days.ago)
.where("properties.property_reminder_date < :date OR properties.property_reminder_date IS NULL", date: 30.days.ago)
.where('properties.id NOT IN (SELECT DISTINCT(property_id) FROM transactions)')

这将为我提供需要通过电子邮件发送给的用户,但是,访问每个用户的属性会显示所有属性,而不是我基于SQL查询所需的属性。

再次编辑:

我能够以一种非常混乱的方式实现我想要的东西:

@testusers = User.joins(:properties)
.where("properties.updated_at < :date", date: 30.days.ago)
.where("properties.property_reminder_date < :date OR properties.property_reminder_date IS NULL", date: 30.days.ago)
.where('properties.id NOT IN (SELECT DISTINCT(property_id) FROM transactions)')
@testusers = @testusers.uniq
@testusers.each do |user|
propertyList = user.properties.active.has_not_updated
UserMailer.with(properties: propertyList, user: user).check_listing.deliver
propertyList.each do |property|
property.update_columns(property_reminder_date: Time.now )
end
end

房地产模型:

...
scope :active, -> { where('expires_at >= ?', Time.now) }
scope :has_not_updated, -> {active.where("updated_at < :date", date: 30.days.ago).where("property_reminder_date < :date OR property_reminder_date IS NULL", date: 30.days.ago).where('id NOT IN (SELECT DISTINCT(property_id) FROM transactions)') }

您可以执行以下操作:

properties.group_by(&:user).each do |user,  properties|
UserMailer.send_email(user, properties).deliver_later
end

在每次迭代中,您将拥有用户和用户属性数组。

最新更新