当 Rails 模型布尔字段设置为 true 而不是 false 时触发电子邮件发送

发布于 2024-12-10 10:08:12 字数 205 浏览 0 评论 0原文

我的应用程序中有两个模型。家庭有很多个人的。个人属于家庭。

我试图做到这一点,以便当家庭模型中的布尔字段设置为“true”时,当家庭“更新”时,电子邮件会发送到针对个人存储的所有电子邮件地址。

谁能帮忙解决这个问题吗?我已经能够在创建个人时足够轻松地让 ActiveMailer 发送电子邮件,但找不到触发特定字段更新的方法?

任何帮助将不胜感激!

I have two models in my application. Families has_many Individuals's. individuals's belongs_to Families.

I'm trying to make it so that when a boolean field in the Families model is set to "true" an email is sent to all of the email addresses stored against Individuals when the family is "updated".

Can anyone help with this? I've been able to get ActiveMailer sending an email when an Individual is created easily enough, but cannot find a way to trigger on the update of a specific field?

Any help would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧时浪漫 2024-12-17 10:08:12

Toby 有正确的想法,但我不同意这应该在控制器中实现......这更适合模型 after_update 回调。像这样的事情:

def update_fired
  if yourfield_changed?
     #send mail here
  end
end

然后只需确保在您的模型中将方法设置为 after_update 回调

Toby has the right idea but I disagree that this should be implemented in the controller... this is much better suited to a model after_update callback. something like this:

def update_fired
  if yourfield_changed?
     #send mail here
  end
end

Then just make sure in your model you set the method to be the after_update callback

源来凯始玺欢你 2024-12-17 10:08:12

也许你可以使用后置过滤器?

关于 Family 模型

after_update :email_individuals


private
def email_individuals
  if boolean_field_changed?
    individuals.each do |i|
      // send out emails here
    end
  end
end

下一步是将其移出请求周期并移入队列。

希望我正确地理解了你的问题。

Maybe you could use an after filter?

on the Family model

after_update :email_individuals


private
def email_individuals
  if boolean_field_changed?
    individuals.each do |i|
      // send out emails here
    end
  end
end

The next step would be to move this out of the request cycle and into a queue.

Hope I grokked your question properly.

微凉徒眸意 2024-12-17 10:08:12

最简单的方法是在控制器的更新操作中添加一些内容

if individual.boolean_field_changed? and individual.boolean_field
  individuals.each do |ind|
    Mailer.deliver_mail(ind)
  end
end

Rails 有一个 API 用于检测模型字段中的更改(在上面的情况下,您将 _changed? 添加到字段名称中,它会告诉您该字段是否已更改。

Easiest way would be to add something to the update action of your controller

if individual.boolean_field_changed? and individual.boolean_field
  individuals.each do |ind|
    Mailer.deliver_mail(ind)
  end
end

Rails has an API for detecting changes in model fields (in the above case you add _changed? to the field name and it will tell you if the field has been changed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文