Ruby on rails 根据上下文自定义验证错误消息
我需要根据表单的上下文和位置,为同一个模型提供不同的错误消息 对于验证名是否存在的Ruby on rails 根据上下文自定义验证错误消息,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我需要根据表单的上下文和位置,为同一个模型提供不同的错误消息 对于验证名是否存在的用户模型: 在后台页面中,可以显示验证消息“First name不能为空” 在注册页面中,信息应为“请键入您的名字” 我正在寻找一个干净的、面向最佳实践的解决方案,因为我不想使用视图助手之类的工具 感谢您的任何提示,您可以在用户模型中使用该方法。像这样的 validate do |user| if user.first_name.blank? && user.id.blank? # i
用户
模型:
- 在后台页面中,可以显示验证消息“First name不能为空”
- 在注册页面中,信息应为“请键入您的名字”
用户
模型中使用该方法。像这样的
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
可能正在使用
隐藏的\u字段
和属性访问器
,我希望您能实现您想要的
表格1:
config/locales/en.yml
希望它能有所帮助:)这是一个好主意,但这并不是一个很好的实践,因为它绕过了rails表单验证。另外,来自后台的
create
操作将显示错误的错误消息。哈哈,这太简单了,只需在base
中添加错误即可。更新了代码。试试看。我想这是最理想的方法。谢谢你的努力,但我真的不想像你建议的那样使用validate来绕过rails在it源代码上的验证。我更喜欢寻找消息替换解决方案
<%= f.hidden_field :check_form, :value => true %>
<%= f.hidden_field :check_form, :value => false %>
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
en:
activerecord:
attributes:
user:
first_name: ""
errors:
models:
user:
attributes:
first_name:
blank: "Please type your first name"