【问题标题】:Customize validation error message depending on the context根据上下文自定义验证错误消息
【发布时间】:2014-04-27 05:01:46
【问题描述】:

根据表单的上下文和位置,我需要为同一模型提供不同的错误消息。

对于验证first_name 存在的User 模型:

  • 在后台页面中可以显示验证消息“名字不能为空”
  • 在注册页面中的消息应该是“请输入您的名字”

我正在寻找一个干净且面向最佳实践的解决方案,因为我不想使用视图助手等进​​行破解。

感谢任何提示,谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    您可以在User 模型中使用validate 方法。像这样的

    validate do |user|
     if user.first_name.blank? && user.id.blank? 
       # id blank means the user is in registration page as he is new user. 
       user.errors.add(:base, "Please type your first name")
     elsif user.first_name.blank?
       user.errors.add(:base, "First name can't be blank")
     end
    end
    

    【讨论】:

    • 好主意,但这并不是真正的好做法,因为它绕过了表单验证。此外,来自后台的 create 操作会显示错误的错误消息。
    • 哈哈,太简单了,在base加个错误就行了。更新了代码。尝试一下。我想这是最理想的方式。
    • 感谢您的努力,但我真的不想按照您的建议使用 validate 来绕过源代码上的 rails 验证。我更喜欢寻找消息替换解决方案
    【解决方案2】:

    可能是用hidden_fieldattr_accessor,希望你能达到你想要的,

    表格一:

    <%= f.hidden_field :check_form, :value => true %>
    

    表格2:

    <%= f.hidden_field :check_form, :value => false %>
    

    您还需要将 check_form 值传递给模型。

    型号:

    attr_accessor :check_form
    validates_presence_of :first_name, :if => :check_form_is_true?, :message => "First Name can't be blank"
    validates_presence_of :first_name, :unless => :check_form_is_true? //here you need to use i18n oriented translation to show the custom error message
    
    private
    def check_form_is_true?
      check_form == true
    end
    

    config/locales/en.yml

    en:
      activerecord:
        attributes:
          user:
            first_name: ""
        errors:
          models:
            user:
              attributes:
                first_name:
                  blank: "Please type your first name"
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-18
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多