ivanibash
ivanibash

Reputation: 1491

Rails not keeping session data when doing ajax with remote=true

I am working with a rails app and trying to do an ajax request with rails remote: true . The request is supposed to trigger one of my controller actions.

<%= form_tag my_action_path(@version), {remote: true} do %>

In the application controller there is a before_filter callback which executes before the action is performed. It checks for session user id like so:

if session[:user_id]

This check fails forcing redirect. When I check session[:user_id] it's nil, which I guess means that the session cookie is not passed. I have a bunch of js that do ajax to the controllers and interestingly they all work, passing the check. So two questions:

Do I need some extra code to make remote:true work? Is there a way of setting a session cookie or smth?

Is this a correct way of verifying unauthorised ajax requests or is there a better way.

I'm using Rails 4

Thanks

Upvotes: 3

Views: 571

Answers (1)

Billy Ferguson
Billy Ferguson

Reputation: 1439

I'm using devise, so I'm not sure if this is directly applicable, however, you also have to pass the authenticity_token in the form tag as well.

<%= form_tag my_action_path(@version), {remote: true}, authenticity_token: true do %>

It might be something separate, but similar. I think this will just work for you though.

Another thing to look at is look at a form that works and look at what data is posted to your server in the console, because rails echoes the data passed to the server and you can use this to help us help you debug. It should have session_id or authenticity_token or something similar in all session requests that work (anything you do while you're logged in).

Upvotes: 3

Related Questions