Sebastian Zeki
Sebastian Zeki

Reputation: 6874

How to write find clause using where user_id =current_user.id

I have a one to many relationship between 1 user and many challenges. I am using rails 4 with Devise

I would like to list the challenges for the current user.

So far I have

@challenge = User.find(current_user.id).challenges

and I've also tried

@challenge = User.find(current_user).challenges

and I also tried @challenge = current_user.challenges

but it doesn't work. I get the error "undefined methodeach' for nil:NilClass"` which usually means @challenge isn't being passed over to the view Have I made some kind of syntax error?

if I do User.find(1).challenges in the rails console it works fine so presumably I'm not using current_user.id correctly

Upvotes: 0

Views: 240

Answers (1)

abhishek77in
abhishek77in

Reputation: 1896

It looks like when you are trying to access the page user is not logged in and hence current_user is set to nil.

current_user.challenges will do the job of fetching all challenges associated to this user. You can use user_signed_in? method from devise before calling this code to ensure current_user is always available.

Upvotes: 1

Related Questions