Rails display current controller errors -


the problem simple. want display error notifications outside simple_form_for tag every controller in app.

i use following code:

- if @user.errors.present?   .alert-box.alert{ data: { alert: true } }     %div= t('simple_form.error_notification.default_message') 

which ok, 1 controller @user variable. want know if there clever way class instance variable (@user) without hardcoding name. in each controller different corresponds current controller name @user userscontroller etc.

thanks help. unfortunately can accept 1 answer :)

possible solution

i end helper method:

  def errors_present?     # returns string "userscontroller" support name-spaced controllers     controller_name = controller.class.to_s.split('::').last      # extract out "user" portion     prefix_name = controller_name.gsub(/controller/i, '').singularize.downcase      # there defined instance variable name?     i_var = controller.instance_variable_get(:"@#{prefix_name}")      return i_var.errors.present? if i_var != nil      false   end 

and view code:

- if errors_present?   .alert-box.alert{ data: { alert: true } }     %div= t('simple_form.error_notification.default_message') 

if you're going in dynamic route you'll need ensure instance variable use matches can inferred controller name. can use in helper method.

  def controller_error_present     # returns string "userscontroller" support name-spaced controllers     controller_name = controller.class.to_s.split('::').last      # extract out "user" portion     prefix_name = controller_name.gsub(/controller/i, '').singularize.downcase      # there defined instance variable name?     controller.instance_variable_get(:"@#{prefix_name}") != nil   end 

to used like:

- if controller_error_present  .alert-box.alert{ data: { alert: true } }     %div= t('simple_form.error_notification.default_message') 

as long initialize @user variable in controller picked instance variable check.


Popular posts from this blog