如何仅在 ruby/rails 中满足对象关系的条件时才执行函数?



我的问题可能不是很清楚,最好用一个例子来说明。。。我有一个帐户模型,它有很多用户(属于帐户(。我在邮件程序中也有一个方法,只有当用户相关的帐户的state"active"时,我才想运行该方法。基本上,只有当帐户处于活动状态时,才应该向用户发送电子邮件。mailer文件中的方法目前看起来是这样的。

def pending_mail(document, user)
@user = user
mail(to: user.email, subject: t('emails.pending.subject') ... do |format|
format.text
format.html
end    
end

只有mailers的工作是呈现和发送电子邮件,而不是处理业务逻辑。邮件收发员的工作不是决定谁能收到电子邮件。

这应该在控制器中处理。例如:

class AccountsController < ApplicationController
def update
if @account.update(account_attributes)
Accounts::UsersNotificationJob.perform_later if @account.active?
redirect_to @account
else
render :new
end
end
end
module Accounts 
class UsersNotificationJob
def perform(account)
account.users.each do |user|
UserMailer.pending_mail(user).deliver
end 
end
end
end

您应该可以通过user.account访问拥有的帐户,这取决于您的模型是如何定义的。在这种情况下,您可以使用一个简单的if语句。

if @user.account.state == "active"
mail blabla do |format|
.....
end
end

最新更新