ActiveRecord属性の元の値(=データベースからロードされた値)を取得する方法はありますか?
このようなものをオブザーバーに入れたい
before_save object
do_something_with object.original_name
end
タスクは、更新時にオブジェクトをハッシュテーブルから削除する(実際には、オブジェクトをテーブル内の別のキーに移動する)ことです。
ActiveRecord属性の元の値(=データベースからロードされた値)を取得する方法はありますか?
このようなものをオブザーバーに入れたい
before_save object
do_something_with object.original_name
end
タスクは、更新時にオブジェクトをハッシュテーブルから削除する(実際には、オブジェクトをテーブル内の別のキーに移動する)ことです。
回答:
_was属性に追加すると、以前の値が得られます。
以下のLucas Andradeの回答からコピー:https : //stackoverflow.com/a/50973808/9359123
追加の_wasレール5.1で廃止され、今では、追加すべきです_before_last_save
何かのようなもの:
before_save object
do_something_with object.name_before_last_save
end
データベースで最後に保存する前に名前の値を返します(保存と作成で機能します)ドキュメントと
の違い:_was_before_last_save
_ ドキュメントからのソースでした
def attribute_was(attr)
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
ドキュメントからの_before_last_saveソース
def attribute_before_last_save(attr_name)
mutations_before_last_save.original_value(attr_name)
end
_was。
追加の_wasレール5.1で廃止され、今では、追加すべきです_before_last_save
何かのようなもの:
before_save object
do_something_with object.name_before_last_save
end
データベースで最後に保存する前に名前の値を返します(保存と作成で機能します)ドキュメントと
の違い:_was_before_last_save
_ ドキュメントからのソースでした
def attribute_was(attr)
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
ドキュメントからの_before_last_saveソース
def attribute_before_last_save(attr_name)
mutations_before_last_save.original_value(attr_name)
end
attribute_wasの代わりに非推奨になりましたがattribute_in_database、attribute_before_last_save 5.1の時点で完全に新しいメソッドであり、以前のバージョンのRailsには同等のメソッドがありませんでした。出典:github.com/rails/rails/pull/25337#issuecomment-225166796
ActiveRecordのattributes_before_type_castメソッドは、型キャストと逆シリアル化が行われる前に属性のハッシュを返します。
Railsのドキュメントをご覧ください
http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
Model.attribute_wasは以前の値を返します:D
self.context:self.context_was