ruby-on-rails - 手动失败#update_attributes保存在Rails中

标签 ruby-on-rails activerecord error-handling

我正在调用@foo.update,并在要更新的属性1的内部,正在def attribute=的模型类中调用write方法(foo),并希望它有条件地使整个更新失败。我可以放什么东西?我尝试使用errors[:base],但它不会使save失败。我也不能使用validates,因为该属性在保存之前会被转换成其他东西。

  def attribute=(attr)
    if bar
      # code to fail entire db save
    end
  end

最佳答案

您可以只检查before_save模型中foo.rb回调上的条件,如果不想保存,则返回false。

before_save :really_want_to_save?

private

def really_want_to_save?
  conditional_says_yes ? true : false
end

如果您也想要错误消息,那么
def really_want_to_save?
  if conditional_says_yes
    true
  else
    errors[:base] << "failed"
    false
  end
end

关于ruby-on-rails - 手动失败#update_attributes保存在Rails中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44336900/

相关文章:

ios - 适用于核心数据的类似 ActiveRecord 的 ORM

java - Google App Engine 中的 e.printStackTrace

http - Play Framework : How to process server errors in HTTP filters?

ruby-on-rails - 主要 :Object (NameError) 的未定义局部变量或方法 `user'

javascript - 如何使用 Jquery 更新数据确认属性内的消息?

ruby-on-rails - 如何使用apache bench在url中指定查询字符串

ms-access - 错字不会在Access VBA中触发错误处理

ruby-on-rails - 如何在 Rails 3 中呈现 View 后调用方法

mysql - 我想将整个 MySQL 表作为数组读入 ruby​​。我正在使用事件记录

ruby-on-rails - 如何覆盖 Rails 模型中的列?