views:

170

answers:

4

Hello,

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. If not, please contact your doctor.

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

+3  A: 

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.

Randy Simon
Okay, but how does that code know which form you want?
Time Machine
@Koning: add @user before it!
Time Machine
@Koning: Thanks!
Time Machine
A: 

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.

j t
A: 

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.

klew
A: 

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.

Tim Rosenblatt