Question

I'm trying to get the current controller for an Error Notification.

helper.rb

  def error_message_for(field, options = {:prepend_text => "#{'<i class="fa fa-bullhorn"></i> '}"}, controller = {:current => "@" + params[:controller] })
    error_message = controller[:current].errors[field][0]
    if error_message
      raw "#{options[:prepend_text]} #{error_message}"
    end
  end

But I'm getting a NoMethodError undefined methoderrors' for "@screens":String`

What am i missing ?

Était-ce utile?

La solution

errors method is accessible on ActiveRecord::Base objects i.e., in your case on instances of your model(Screen) which extend ActiveRecord::Base.

Currently you receive error as NoMethodError undefined method errors for "@screens":String because you are not invoking errors method on a String ("@screens") instead of an instance of your model. "@screens" is a String formed by concatenating "@" + params[:controller], it is NOT an instance variable @screens.

So, you would need to pass an instance of your model class to your error_message_for method and then call errors on it.

For example:

  def error_message_for(object, field, options = {:prepend_text => "#{'<i class="fa fa-bullhorn"></i> '}"}})
    error_message = object.errors[field][0]
    if error_message
      raw "#{options[:prepend_text]} #{error_message}"
    end
  end

Call it as below:

<%= form_for(@screen) do |f| %>
  <%= error_message_for(@screen,:field_name) %>
<% end %>

Autres conseils

If you want to have the error message for a field in a form you can get it by doing something like this:

<%= form_for(@screen) do |f| %>
  <%= f.object.errors.get(:field_name) %>
<% end %>

Or with a helper

# in view
<%= error_message_for(f, :field_name) %>

# in helper
def error_message_for(form_object, field_name, ...)
  error_messages = form_object.object.errors.get(field_name)
  if error_messages.present?
    raw "#{...} #{error_messages.first}"
  end
end

Benefit of this solution is that you do not need to pass around the object (@screen) itself what makes it easier to use this code with nested forms.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top