Question

Here the call in view:

<%= f.label form_val(:name) %>

Here's the custom helper:

def form_val(input)
   if @user.errors[input].blank?
     input
   else
     @user.errors[input].to_sentence
   end
end

The above works and if there is a form error the input label will display the validation error. Now I need to add Input: to the beginning of the error and a class at the end. Thus displaying:

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

I've tried the following as it makes sense, but I'm getting an SyntaxError:

def form_val(input)
  if @user.errors[input].blank?
    input
  else
    input, @user.errors[input].to_sentence, class: "some_class"
  end
end
Was it helpful?

Solution

You are trying to return method arguments as a return from a method. Methods can only return one value; be it int, string, or class object. Your syntax error is because it is trying to return 3 values.

What you may want to do is create a helper method for the view or in app/helpers/application_helper.rb. This way you can return the f.label call with the proper arguments as you desire. Something like:

def error_helper(input, form)
  if @user.errors[input].blank?
    return form.label(input)
  else
    return form.label(input, @user.errors[input].to_sentence, class: "some_class")
  end
end

I like parenthesis in this situation for readability. I am sure this can be written using a better technique but maybe this will get you on the right track?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top