【发布时间】:2014-04-27 05:01:46
【问题描述】:
根据表单的上下文和位置,我需要为同一模型提供不同的错误消息。
对于验证first_name 存在的User 模型:
- 在后台页面中可以显示验证消息“名字不能为空”
- 在注册页面中的消息应该是“请输入您的名字”
我正在寻找一个干净且面向最佳实践的解决方案,因为我不想使用视图助手等进行破解。
感谢任何提示,谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4
根据表单的上下文和位置,我需要为同一模型提供不同的错误消息。
对于验证first_name 存在的User 模型:
我正在寻找一个干净且面向最佳实践的解决方案,因为我不想使用视图助手等进行破解。
感谢任何提示,谢谢
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4
您可以在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加个错误就行了。更新了代码。尝试一下。我想这是最理想的方式。
可能是用hidden_field和attr_accessor,希望你能达到你想要的,
<%= f.hidden_field :check_form, :value => true %>
<%= 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
en:
activerecord:
attributes:
user:
first_name: ""
errors:
models:
user:
attributes:
first_name:
blank: "Please type your first name"
希望对你有帮助:)
【讨论】: