Ruby-on-rails 如何向 Rails 模型添加错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17411235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:16:31  来源:igfitidea点击:

How to add errors to Rails model?

ruby-on-rails

提问by SonIcco

I tried to add an exception in the before_savemethod in a rails model, but in the view, no error message exists.

我试图before_save在rails模型中的方法中添加异常,但在视图中,不存在错误消息。

Model:

模型:

before_save do
    doing_some_stuff
    begin
      File.open('some_file', 'w+') do |file|
        if file.write(file_content)
          return true
        else
          return false
        end
      end
    rescue => e
      self.errors.add(:base, e.message) 
      return false
    end

View:

看法:

<%= @model.errors.any? %>

This is always false.

这总是错误的。

How do I add error messages to the model?

如何向模型添加错误消息?

EDIT:

编辑:

The problem was, I had a redirect after the update_attribute function instead of rendering the action again. Thx for help.

问题是,我在 update_attribute 函数之后进行了重定向,而不是再次呈现该动作。谢谢你的帮助。

回答by Chris Heald

You should be performing this on validation, not on before_save. By the time you get to the before_savecallback, the record is assumed to be valid.

您应该在验证上执行此操作,而不是在before_save. 当你到达before_save回调时,记录被认为是有效的。

validate do
  doing_some_stuff
  begin
    File.open(some_file, 'w+') do |file|
      if !file.write(file_content)
        self.errors.add(:base, "Unable to write #{some_file}")
      end
    end
  rescue => e
    self.errors.add(:base, e.message)
  end
end