Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to respond to an ajax call in before_filter

I write a before_filter like this:

def authenticate_user
  if request.xhr?
    flash.now[:alert] = 'Error'
    render :partial => "js_helpers/popover", :formats => :js
  else
    authenticate_user!
  end
end

However, it doesn't work as expected. The log file shows:

  Rendered js_helpers/_popover.js.erb (0.1ms)
Filter chain halted as :authenticate_user rendered or redirected

The function of the js code is to show a popover block showing flash message. but it looks like the js code is not excited at all.

So, I changed my way:

def authenticate_user
  if request.xhr?
    flash.now[:alert] = 'Error'
    render :js => "window.location = '/users/sign_up'"
  else
    authenticate_user!
  end
end

Instead, I want to redirect to sign up page.

However, there is still problems. the flash seems not work

How can I achieve my goal:

when the request is an ajax call, execute come javascript code or redirect_to a new page. Under both condition, I need to store some message in flash.

Plus, the javascript code is very long so that I need to put it in a file. How can I use render :js to execute a javascript inside a file?

like image 912
HanXu Avatar asked Mar 28 '12 15:03

HanXu


1 Answers

I think that instead of trying to render javascript code for the client to execute, you should return a json response that your client will understand.

def authenticate_user
  if request.xhr?
    render :json => { alert: 'Error', redirect: sign_up_path }, :status => 403
  else
    authenticate_user!
  end
end

In your ajax calls, trap the 403 status code, display the alert message, and redirect to the given url. You should be able to make this a standard hook for a 403 (or whatever status code seems most appropriate) so that it can be as DRY as the before_filter.

like image 165
sockmonk Avatar answered Sep 26 '22 05:09

sockmonk