【问题标题】:Display error from before_save callback in rails admin在 rails admin 中显示 before_save 回调的错误
【发布时间】:2016-02-25 18:49:00
【问题描述】:

我正在尝试为可以在rails_admin 中创建的对象创建回调。我是我的模型,我有以下 before_save 回调。

def check_remaining
  if c.purchased_a == 0
    errors.add(:base, "Some error message here")
  end
end

如果用户去创建所述对象时回调中的条件为真,我试图在 rails_admin 中显示错误消息。在他们点击保存后,我希望会显示错误消息,但实际上会创建对象。

【问题讨论】:

    标签: ruby-on-rails callback rails-admin


    【解决方案1】:

    在保存之前不要使用before_save 来验证您的模型。您应该改用validate。试试这样的:

    class Foo < ActiveRecord::Base
      belongs_to :c  # As you mark somewhere.
      validate :check_remaining
    
      def check_remaining
        errors.add(:base, "Some error message here") if c.purchased_a == 0
      end
    end
    

    说明

    validate 用于向您的模型添加自定义验证。即使未保存模型也会发生这种情况。您可以随时使用model.errors 检查模型错误。

    before_save 回调happens after 模型验证。因此,在那里进行验证根本不起作用,因为它们不会被评估。 before_save 用于设置属性,或计算某个值,诸如此类。

    希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      由于 C 是该对象所属的另一个模型,因此您将 if 语句更改为:

      if self.c.purchased_a == 0

      【讨论】:

      • c 来自一个belongs_to
      • 那就试试 self.c.purchased_a==0
      • 不会改变任何东西。回调 get 运行,但我需要在 rails-admin 页面中显示错误
      • 如果您向我展示将其传递给模型的控制器,我可以向您展示如何将其显示在视图中。
      【解决方案3】:

      在模型中捕获错误的标准方法:

      正如这里所说的ActiveModel::Errors < Object

      class Foo < ActiveRecord::Base
      
        # Required dependency for ActiveModel::Errors
        extend ActiveModel::Naming
      
        def initialize
          @errors = ActiveModel::Errors.new(self)
        end
      
        attr_accessor :purchased_a
        attr_reader   :errors
      
        def validate!
          errors.add(:purchased_a, "Some error message here") if c.purchased_a == 0
        end
      
      end
      

      以上允许您这样做:

      Foo = Foo.new
      Foo.validate!            # => ["Some error message here"]
      Foo.errors.full_messages # => ["purchased_a Some error message here"]
      

      我不确定 c.purchased_ac 的来源或来源。 请修改代码。

      【讨论】:

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