CaptainM / workout_journal

Daily workout suggestions and private log.
0 stars 0 forks source link

Authentication and Ajax requests #21

Closed CaptainM closed 9 years ago

CaptainM commented 9 years ago

@harimohanraj89 @htella @DrRobotmck Hello! I'm having some trouble integrating my Exercise controller with ajax and authentication.

My user path authentication and authorization is working just fine. I wanted to add a before_action :authenticate to my exercise controller, because I don't want my users to see the workouts unless they are logged in.

When I add before_action :authenticate to the top of my Exercise Controller, my ajax requests seemingly stops working (there are no errors anywhere, but youtube doesn't request a video, and the description doesn't automatically pop open when I hover over the exercise name).

I'm guessing there's something to do with the timing of things. Ajax requests have to wait for authentication before running, perhaps? There is kind of a lot about this on the internet, but I've read through a bunch of articles and I've having trouble aligning their problem with my own. Do I need to send the session's id with every Ajax request in my javascript file?

harimohanraj89 commented 9 years ago

Have you made use of binding.pry inside the controller actions that appear to be non-functioning to investigate whether your Rails application is able to correctly identify that you are logged in? You shouldn't have to do any extra work to ensure that Rails recognizes the current user even through AJAX requests.

CaptainM commented 9 years ago

Ok! So I figured out that it has nothing to do with the before authorization! ANYTIME that I click on the "Workout Journal" link which resides at the top of every page, the ajax requests stop responding. Below is the code I have in my application.html.erb to link to the root path.

<h1><b><%= link_to "Workout Journal", root_path %></b></h1>

Now, on to find out why that link is making my JS not work...(when I navigate to the root path directly, everything is fine).

harimohanraj89 commented 9 years ago

This sounds like a classic Rails + JavaScript problem, brought about by a component of Rails called Turbolinks. You can circumvent this problem by following the instructions in this post.

In essence, if your file looks like this right now:

$(function() {
  // do some stuff
});

then it needs to be modified to look like this:

var initialize = function() {
  // do some stuff
}

$(document).ready(initialize);
$(document).on('page:load', initialize);