Reputation: 9573
In my Rails app I'm using AngularJS and would like to display all submissions to the site that are associated to the :current_user; I use Devise.
Here is my factory:
var brainDB = angular.module('brainDB',['ngResource']).factory('userSubmission', function($resource){
var service = $resource('/api/:user_id/submissions/:id', {user_id: '@user_id'}, {id: '@id'} );
return service;
});
My Angular controller:
brainDB.controller('SubmissionsCtrl',['$scope', 'Submission', 'userSubmission',
function($scope, Submission, userSubmission){
$scope.submissions = Submission.query();
$scope.userSubmissions = userSubmission.query();
}]);
And here is relevant code from my submissions controller:
def usersubmission
@submissions = current_user.submissions
@submission = @submissions.find(params[:id])
render json: @submission
end
I have set up a route, "/api/:user_id/submissions/:id" which works just fine if you visit it in your browser with a valid user_id. However, I don't know how to tell Angular what the current_user.id is. How should I go about doing this? I've been trying all day and am desperate.
Upvotes: 0
Views: 350
Reputation: 4197
When your page is built you would have session scope already. We did something like this by simply passing session id to an app level JavaScript variable in view layout, in our case we use HAML
. Something like below in head block before ng-app
kicks in.
globalAppCtx = {}
globalAppCtx['user'] = JSON.parse("#{escape_javascript session[:user].to_json}");
In above code, session[:user]
is ruby session with user literal containing relevant Hash that was required in ng-app
. Else where, in the angular code or elsewhere in JavaScript, you can refer to globalAppCtx['user']
IMO this shouldn't be very expensive and saves you an AJAX
request to get the value. I could not think of any downside of this approach.
Upvotes: 0