3
  def current_user
    @_current_user ||= session[:current_user_id] &&
      User.find_by_id(session[:current_user_id])
  end

Is @_current_user simply an id or a user object found by its id?

4

2 回答 2

1

To answer your question directly: A user object found by its id or nil if there is no :current_user_id value in the session or if no user object exists for that id.

Basically, if @_current_user is already set then it won't change it. Otherwise, then it checks if session[:current_user_id] exists/is set, and if it is, by nature of the && operator, the right side is returned as the value of the expression. The right side basically looks up the user with that current_user_id.

Even simpler: If @_current_user isn't set yet, then if the session has a current_user_id value, it sets @_current_user to the User object matching that user id.

于 2013-03-31T00:31:44.520 回答
0

If we assume session[:current_user_id] is 5, then the && operator with the User model will return the User instance:

> 5 && User.new(:name => 'Foo')
=> #<User name="Foo"> 

If both sides of the && operator are "truthy" (meaning neither undefined or false), then the right-hand side value is returned by the && operator. So @_current_user will be the User instance.

于 2013-03-31T00:29:09.420 回答