Rails,用脏了还是改了?带有 after_commit 的标志

发布于 2024-11-30 21:42:28 字数 194 浏览 1 评论 0原文

我听说 Rails 有一个脏/更改标志。是否可以在 after_commit 回调中使用它?

在我的用户模型中,我有:

after_commit :push_changes

def push_changes 中,我想要一种方法来知道名称字段是否更改。这可能吗?

I heard rails has a dirty/change flag. Is it possible to use that in the after_commit callback?

In my user model I have:

after_commit :push_changes

In def push_changes I would like a way to know if the name field changed. Is that possible?

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

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

发布评论

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

评论(3

谈情不如逗狗 2024-12-07 21:42:28

您可以在 after_commitprevious_changes strong> 访问保存模型之前的模型属性值。

请参阅这篇文章以获取更多信息:
属性的 after_commit

You can use previous_changes in after_commit to access a model's attribute values from before it was saved.

see this post for more info:
after_commit for an attribute

相守太难 2024-12-07 21:42:28

您可以做一些事情来检查...

首先,您可以检查单个属性:

user = User.find(1)
user.name_changed? # => false
user.name = "Bob"
user.name_changed? # => true

但是,您也可以检查整个模型中哪些属性已更改:

user = User.find(1)
user.changed     # => []
user.name = "Bob"
user.age = 42
user.changed     # => ['name', 'age']

您还可以做更多事情 - 检查请访问 http://api.rubyonrails.org/classes/ActiveModel/Dirty.html 了解详细信息。

编辑:

但是,考虑到这是在 after_commit 回调中发生的,模型已经被保存,这意味着保存之前发生的更改的知识会丢失。您可以尝试使用 before_save 回调自行挑选更改,将它们存储在某处,然后在使用 after_commit 时再次访问它们。

You can do a few things to check...

First and foremost, you can check an individual attribute as such:

user = User.find(1)
user.name_changed? # => false
user.name = "Bob"
user.name_changed? # => true

But, you can also check which attributes have changed in the entire model:

user = User.find(1)
user.changed     # => []
user.name = "Bob"
user.age = 42
user.changed     # => ['name', 'age']

There's a few more things you can do too - check out http://api.rubyonrails.org/classes/ActiveModel/Dirty.html for details.

Edit:

But, given that this is happening in an after_commit callback, the model has already been saved, meaning knowledge of the changes that occurred before the save are lost. You could try using the before_save callback to pick out the changes yourself, store them somewhere, then access them again when using after_commit.

香草可樂 2024-12-07 21:42:28

从 Rails 5.1 开始,在 after_commit 中,您应该使用 saved_change_to_attribute?

参考:Rails 5.1.1 弃用警告已更改_attributes

Since Rails 5.1, in after_commit you should use saved_change_to_attribute?

Ref: Rails 5.1.1 deprecation warning changed_attributes

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