问题:试图开发一个 cron 作业或延迟作业来发送自动回复电子邮件消息。事实证明这是我认为的一个更棘手的问题。这是我的模型:
class List < ActiveRecord::Base
has_many :subscriptions
has_many :contacts, :through => :subscriptions
has_many :messages
class Subscription < ActiveRecord::Base
belongs_to :contact
belongs_to :list
class Message < ActiveRecord::Base
belongs_to :user
belongs_to :list
-----------Lists------------
| |
| |
Subscriptions (join) Messages
|
|
Contacts
我的目标是遍历所有订阅,并为每个订阅检查“订阅后天数”是否与消息对象上的“注册后天数”属性相匹配。如果为真,则将消息传递给收件人,然后继续循环遍历其他消息。
class SubscriptionsController < ApplicationController
def deliver
@subscriptions = Subscription.all
@subscriptions.each do |subscription|
subscription.list.messages.each do |message|
if message.days_since == subscription.days_after
# deliver message through mailer in a scheduled delayed_job
else
end
end
end
end
如果有人在 2 天前订阅了一个列表,而列表所有者希望在注册后 2 天发送一条消息,那么该消息应该被发送,因为它是匹配的。
上面的 deliver 方法是我尝试循环遍历所有订阅,并将 subscription.days_since 与 message.days_after_signiup 进行比较。
如有任何建议或想法,我们将不胜感激。真的一直在为这个问题而苦苦挣扎,能够通过这个障碍感觉很棒。
D.
最佳答案
您不能只使用 where 或 join 语句做一些事情吗?
messages = Message.joins(:subscriptions).where("messages.days_since > subscriptions.days_after")
messages.each do |message|
message.deliver
end
关于ruby-on-rails - Rails 一个 parent ,两个 child ,通过 parent 访问其他 child 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17332551/