goo goo - 3 months ago 16
AngularJS Question

Rails + Angularjs: Passing user_id with JSON

I'm building a simple blog app using Rails 4 (api) & Angularjs to help with learning Angularjs. I've already spent 2 days just getting my post model to communicate with Angularjs. It seems I've hit another wall trying to associate the posts with a user (using Devise).

I know that as I build on to this app, that I'll be using foreign keys & so I would love to hear from others who have built SPAs using rails & angularjs. I also tried to set Angularjs up to mimic Rails as close as possible.

How do you handle associations using Angularjs & Rails?

How do you even get Devise helpers, such as

current_user
&
user_signed_in?
to work in Angularjs templates?


Thank you in advance.

I can add more details if you need me to. I really just don't know where to go form here (I'm a newbie in both Rails & Angularjs)

Answer

How do you even get Devise helpers, such as current_user & user_signed_in? to work in Angularjs templates?

The simple answer is, you don't. There can be lots of philosophical debate on this subject, but essentially javascript is unsecure for this purpose because everything is available for a user to inspect in their browser.

If you want to associate a post with a user, you would be best to do so at the controller level in rails. Use current_user to set the user_id field on your Post (or whatever way you want to associate it).

I don't put any 'secure' functionality in my Angular apps.

Here's an example of how I do it in one of my apps where I associate the users organisation with a journey.

def create
    @journey = Journey.new(params[:journey])
    @journey.organisation = current_user.organisation
    if @journey.save
      render json: @journey
    else
      head :error
    end
end

Oh, also in your Api::PostsController you need to call before_filter :authenticate_user! to be able to use current_user

Comments