#ruby-on-rails #activerecord #callback
Вопрос:
Правильно ли я понимаю, что если я выполню
model = Model.create(some_attr: "attr_value")
model.update(some_attr: "new_attr_value")
и для модели у меня есть
before_update :before_update_callback
def before_update_callback
some_attr
end
этот обратный вызов вернет «new_attr_value», поскольку внутренний объект ruby (переменная «модель») изменился до вызова обратного вызова.
Комментарии:
1. Возврат из обратного вызова ничего не делает, но да, значение
some_attr
будет новым значением в этот момент. Значениеsome_attr_changed?
будетtrue
, и старое значение будет вsome_attr_was
.2. @rmlockerd до Rails 5 возврат false из обратного вызова приведет к прерыванию операции.
Ответ №1:
ДА. Именно это и произойдет.
# Updates the attributes of the model from the passed-in hash and saves the
# record, all wrapped in a transaction. If the object is invalid, the saving
# will fail and false will be returned.
def update(attributes)
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
assign_attributes(attributes)
save
end
end
Видеть: