【问题标题】:ActiveRecord before_update callback understandingActiveRecord before_update 回调理解
【发布时间】:2021-07-29 17:06:16
【问题描述】:

如果我执行,我是否理解正确

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​​ 对象(变量“模型”)在回调被调用之前发生了变化。

【问题讨论】:

  • 从回调中返回什么都不做,但是some_attr 的值将是此时的新值。 some_attr_changed? 的值将是 true,旧值将在 some_attr_was
  • @rmlockerd 在 Rails 5 从回调返回 false 之前会中止操作。

标签: ruby-on-rails activerecord callback


【解决方案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

见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多