Search code examples
ruby-on-railsajaxcontrollershort-circuiting

Short Circuit a controller action with xhr for rails


Is there a way to short-circuit an action with a method and ensure that other methods aren't called afterwards in Rails?

def update
   return head(:unauthorized) unless available_user_settings?
   if setting.update....
   ...
end

I would like to do something more like:

def update
   ensure_settings_modifiable!
   if setting.update....
   ...
end

But I don't know of a good way to render head and stop the rest of the action if the settings should not be updated.


Solution

  • You could use before_action something like:

    before_action :ensure_settings_modifiable!, only: [:update]
    
    private
    
    def ensure_settings_modifiable!
      head(:unauthorized) unless available_user_settings?
    end
    

    as the update action won't execute if head is called in a before_action