4
votes

How do I add a custom class to a form_for else statement?

<%= form_for(@user) do |f| %>

      .
      .
      .
      <%= f.label :name, 
        if @user.errors[:name].blank?
          'Name'
        else
          'Name ' + @user.errors[:name].to_sentence
        end
      %>

I've tried:

else
  'Name ' + @user.errors[:name].to_sentence, class: "some_class"
end

Also tried:

else
   'Name ' + @user.errors[:name].to_sentence, :class => "some_class"
end

but both generate unexpected errors.

I'm simply customizing the input label to display the validation error upon form submission and would like to change the text color.

1

1 Answers

3
votes

I guess you can do it in one line:

<%= f.label :name, (@user.errors[:name].blank? 'Name' : 'Name ' + @user.errors[:name].to_sentence) %>

Then:

<% if @user.errors[:name].blank? %>
  <%= f.label :name, 'Name' %>
<% else %>
  <%= f.label :name, 'Name ' + @user.errors[:name].to_sentence, :class => "some_class"  %>
<% end %>