← Back to Upcase

current_user helper method


(Francisco De La Cruz) #1

Hi all, at the end of week four Matthew introduces the current_user helper method and puts it in the ApplicationController. He then uses it in the DeskController starting with the index action as so,

def index
    @decks = Deck.all
end

becomes,

def index
    @decks = current_user.decks
end

I understand that current_user returns an User object if there’s one to return. My question is, where does that decks method come from? A first guess is that is path_helper method. The following is an excerpt from rake routes:

decks GET /decks(.:format) decks#index

But then what about:

def new
    @deck = current_user.deck.new
end

and,

def find_deck
    current_user.decks.find(params[:id])
end

I’ve gotten everything up until this point, but If that’s not it I’m lost.

Thanks in advance, Francisco


(Guille Carlos) #2

I am not taking the Intro to Rails Workshop but!
Check your User model, it should say:

class User
has_many :decks

### other stuff ####

end

Looks like in the first version you are returning ALL decks.
In the second version you are returning the decks owned by the current_user.


(Francisco De La Cruz) #3

Thanks @guillec, that makes sense. I seem to have forgotten about the has_many method in the model.

Still, what about the other two, the new action?

def new
    @deck = current_user.deck.new
end

and the helper method?

def find_deck
    current_user.decks.find(params[:id])
end

(Guille Carlos) #4

In the new action, you are creating a instance of a Deck object and setting the deck.user_id to the current_user.id.

def new
  @deck = current_user.deck.new
end

It would be de same thing to say

@deck = Deck.new
@deck.user_id = current_user.id

In the next one

def find_deck
  current_user.decks.find(params[:id])
end 

You are searching for a Deck that the current_user owns with a specific id.

It would be the same to do

def find_deck
  Decks.where( id: params[:id], user_id: current_user.id)
end 

(Kevin McGladdery) #5

Here are some related resources:

http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

http://api.rubyonrails.org/classes/ActiveRecord/Relation.html