开发者

validates_presence_of + :message shows the name of the field

I'm creating a Rails app, and I have a model called User. In this model I have a boolean value called isagirl. A user must specify if it is a girl or not, which is done by two radio buttons. In my model I have this:

validates_presence_of :isagirl, :message => "You must be either a Boy or a Girl. If not, please contact us."

However, when I don't specify a sex, I'm seeing this:

Isagirl You must be either a Boy or a Girl.

开发者_如何学C

as an error message. The problem is that 'Isagirl' must not be there in the error message. How can I disable that? And no, using CSS to hide it is no option.

Thanks


The way that I do this is to output the message without the field name. For example, I have a partial that outputs the error messages after validation fails.

<ul>
    <% errors.each do |attribute, message| -%>
        <% if message.is_a?(String)%>
            <li><%= message %></li>
        <% end %>
    <% end -%>
</ul>

Notice that this does not output the attribute. You just need to make sure that all your messages makes sense without an attribute name.


In one of my projects I was using custom-err-msg plugin. With it when you specify error message this way:

:message => "^You must be either a Boy or a Girl. If not, please contact us."

(notice ^ at the begining) it won't print attribute name when printing errors. And you can use standard error_messages or error_messages_for helpers.


I don't know how to omit the attribute name in the validates_presence_of function (it can be painful without dirty hacking) but I would use validate function to achieve what you want:

protected
    def validate
      errors.add_to_base("You must be either a Boy or a Girl. If not, please contact us.") if params[:isagirl].blank?
    end

I used specifically method blank? here because validates_presence_of is using blank? for the test you should get this same behavior.

add_to_base is adding general error messages that are not related to the attributes and this saves you from hacking the view.


I recommend using the errors.add_to_base option. Without knowing what your layout looks like, that's going to be the simplest way to get a plain error message to appear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜