ruby-on-rails - 另一个模型的属性上的 Rails 自定义验证错误消息

标签 ruby-on-rails validation rails-activerecord rails-i18n

我在我的模型中使用以下代码将链接插入到验证错误消息中:

class Bar < ActiveRecord::Base
  has_many :foos
  validate :mode_matcher

  def mode_matcher
    self.foos.each do |f|
      errors[:base] << mode_mismatch(foo) unless foo.mode == "http"
    end
  end

  def mode_mismatch(f)
    foo_path = Rails.application.routes.url_helpers.foo_path(f)
    "Foo <a href='#{foo_path}'>#{f.name}</a> has the wrong mode.".html_safe
  end

它运行良好,但我知道推荐的方法是通过语言环境文件。我遇到了麻烦,因为我正在验证另一个模型的属性,因此以下不起作用:
en:
  activerecord:
    errors:
      models:
        bar:
          attributes:
            foo:
              mode_mismatch: "Foo %{link} has the wrong mode."

这样做的正确方法是什么?

最佳答案

ActiveModel 在多个范围内查找验证错误。 FooBar可以为 mode_mismatch 共享相同的错误消息如果您将其包含在 activerecord.errors.messages而不是 activerecord.errors.models :

en:
  activerecord:
    errors:
      messages:
        mode_mismatch: "Foo %{link} has the wrong mode."

将该区域设置字符串与 link 一起使用插值然后变成一个问题
def mode_matcher
  self.foos.each do |foo|
    next unless foo.mode == "http"

    errors.add :base, :mode_mismatch, link: Rails.application.routes.url_helpers.foo_path(f)
  end
end

关于ruby-on-rails - 另一个模型的属性上的 Rails 自定义验证错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057784/

相关文章:

ruby-on-rails - 如何为每个数据库连接执行查询

ruby-on-rails - 使用 Thinking Sphinx 进行多索引全局搜索

组合中的 Spring 验证

ruby-on-rails - 使用 Ruby on Rails Activerecord 中的eager_load 将可计算列添加到多表选择子句

C 用户输入验证 - 只需要一个转换为 int 的字符

java - 在 java 中使用 continue 选项连接 while 循环

ruby-on-rails - 未触发 ActiveRecord after_rollback 回调

ruby-on-rails - JPEG 无法被Identify、Paperclip、ImageMagick on Rails 3.1.3 OSX Mountain Lion 识别

javascript - 对表格进行排序时,会自动选中该复选框

ruby-on-rails - Sidekiq worker 每两秒显示 'ERROR: heartbeat: "\xE 2"from ASCII-8BIT to UTF-8'