Skyalchemist
Skyalchemist

Reputation: 461

Getting current_user's id in model

Forgive me if this is a newb question but I was wondering how they got the current user's id in the User model here:
Listing 10.39 I've tried reading it again and again and i still can't figure it out :(

class User < ActiveRecord::Base
  .
  .
  .
  def feed
    # This is preliminary. See "Following users" for the full implementation.
    Micropost.where("user_id = ?", id)
  end
  .
  .
  .
end

Upvotes: 1

Views: 1378

Answers (1)

Rahul Tapali
Rahul Tapali

Reputation: 10137

feed is an instance level method so self will have user object. So id is equivalent to self.id.

For example: Assume you have user_method in User model.

def user_method
  puts self  #prints user object
  puts self.id #prints user id
  puts id #prints user id
end

user = User.create(user_attributes)
user.user_method

Similarly, feed is called on some user object.

Upvotes: 1

Related Questions