max pleaner
max pleaner

Reputation: 26768

How to use "current_user" with devise in Rails?

The code in question is in the create action of the Article controller. I want each new article created to belong to the currently signed in User.

I checked that there is a user_id column in the Articles table and the correct association statements are in both models.

When I try and submit the form for a new Article, I get this error:

undefined method 'article' for nil:NilClass

in reference to this line of code:

@article = @current_user.article.new(article_params)

Am I using current_user incorrectly? How would one go about making the new item belong to the currently signed in user?

Upvotes: 2

Views: 2201

Answers (3)

Nick Ginanto
Nick Ginanto

Reputation: 32130

current_user is basically a convenience method/variable which takes the user id from the session hash and grabs that user (which is the current user that is active on that specific request)

so, when you want to have something only on the current user, just called current_user

however, there are some things you should watch out

  1. make sure that the current user is logged in. so make sure that when calling current_user.article.new(params) that current_user isn't nil, or it will throw an exception

  2. when you want something to be only on that specific logged in user make sure to do as you did in the question

such as: current_user.articles instead of Article.where(user_id: ...) this will help you avoid problems in the future, and it may be faster in some situations

and 3. I think it should be current_user.articles.new(...)

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

You should use current_user method:

@article = current_user.articles.new(article_params)

@current_user instance variable isn't set (thus it evaluates to nil) until current_user is called.

Upvotes: 4

Satya Kalluri
Satya Kalluri

Reputation: 5214

It should be current_user, not @current_user. current_user is a method, not an instance-variable.

Upvotes: 1

Related Questions