使用Rails我试图得到一个错误消息,如“歌曲字段不能为空”保存。做以下事情:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... 只显示“Song Rep XYW不能为空”,这是不好的,因为字段的标题不是用户友好的。如何更改字段本身的标题?我可以更改数据库中字段的实际名称,但我有多个“song”字段,我确实需要特定的字段名称。
我不想破坏rails的验证过程,我觉得应该有办法解决这个问题。
使用Rails我试图得到一个错误消息,如“歌曲字段不能为空”保存。做以下事情:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... 只显示“Song Rep XYW不能为空”,这是不好的,因为字段的标题不是用户友好的。如何更改字段本身的标题?我可以更改数据库中字段的实际名称,但我有多个“song”字段,我确实需要特定的字段名称。
我不想破坏rails的验证过程,我觉得应该有办法解决这个问题。
当前回答
试试这个。
class User < ActiveRecord::Base
validate do |user|
user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
end
end
我在这里找到了这个。
Rails 3到6的更新:
validate do |user|
user.errors.add(:base, "Country can't be blank") if user.country_iso.blank?
end
这是另一种方法。 您要做的就是在模型类上定义一个human_attribute_name方法。将列名作为字符串传递给该方法,并返回用于验证消息的字符串。
class User < ActiveRecord::Base
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address"
}
def self.human_attribute_name(attr)
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
上面的代码来自这里
其他回答
我建议安装David Easley最初编写的custom_error_message gem(或作为插件)
它可以让你做以下事情:
validates_presence_of :non_friendly_field_name, :message => "^Friendly field name is blank"
在自定义验证方法中使用:
错误。add(:base, "自定义错误消息")
因为add_to_base已弃用。
错误。add_to_base("自定义错误消息")
Rails3 Code与完全本地化的消息:
在模型用户中。Rb定义验证
validates :email, :presence => true
在config locales /和. yml
en:
activerecord:
models:
user: "Customer"
attributes:
user:
email: "Email address"
errors:
models:
user:
attributes:
email:
blank: "cannot be empty"
如果在显示字段名时locale不同,那么Graywh的答案是最好的。对于动态字段名(基于要显示的其他字段),我将执行如下操作
<% object.errors.each do |attr, msg| %>
<li>
<% case attr.to_sym %>
<% when :song_rep_xyz %>
<%= #display error how you want here %>
<% else %>
<%= object.errors.full_message(attr, msg) %>
<% end %>
</li>
<% end %>
else方法中的full_message方法是rails在full_messages方法中使用的方法,因此它将在其他情况下给出正常的rails错误(rails 3.2及更高版本)
我试着跟随,为我工作:)
1 job.rb
class Job < ApplicationRecord
validates :description, presence: true
validates :title,
:presence => true,
:length => { :minimum => 5, :message => "Must be at least 5 characters"}
end
2 jobs_controller.rb
def create
@job = Job.create(job_params)
if @job.valid?
redirect_to jobs_path
else
render new_job_path
end
end
3 _form.html.erb
<%= form_for @job do |f| %>
<% if @job.errors.any? %>
<h2>Errors</h2>
<ul>
<% @job.errors.full_messages.each do |message|%>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<div>
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div>
<%= f.label :description %>
<%= f.text_area :description, size: '60x6' %>
</div>
<div>
<%= f.submit %>
</div>
<% end %>