![](/img/trans.png)
[英]Testing attribute_changed? VS. previous_changes in checking if a specific attribute changed (Rails), behaves differently
[英]Checking if an attribute changed after commit in Rails
我知道使用dirty
或changed?
在before_commit
情況下或在保存模型之前很有用。 模型保存后, previous_changes
給出更改。 這很棒。 但,
如果看起來像,我如何檢查控制器中的特定屬性是否已更改
def update
@item = Item.find(params[:id])
if @item.update_attributes(item_params)
# horray
# check if the :name changed, if so do something about it
else
# d'oh
end
end
有沒有比!@item.previous_changes[:name].nil?
更好的方法!@item.previous_changes[:name].nil?
我不知道是否有更好的方法,但我會這樣做:
if @item.previous_changes.has_key?('name')
# Name has been changed.
end
在 Rails 5 中,您可以使用saved_change_to_attribute?
檢查具體的變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.