2013-03-31 29 views
-1
class ApplicationController < ActionController::Base 

    private 

    # Finds the User with the ID stored in the session with the key 
    # :current_user_id This is a common way to handle user login in 
    # a Rails application; logging in sets the session value and 
    # logging out removes it. 
    def current_user 
    @_current_user ||= session[:current_user_id] && 
     User.find_by_id(session[:current_user_id]) 
    end 
end 

如何理解上面的代碼? ||=是什麼意思?並且是@_current_user一個id或一個用戶對象?另外,爲什麼它始於_什麼是|| =在rails中?

任何人都可以回答我@_current_user是什麼?

+0

該帖子的答案不好。它不回答關於'@ _current_user'的其他問題。 – OneZero

+0

http://stackoverflow.com/questions/8506257/operator-in-ruby-搜索「ruby運營商」。 – 2013-03-31 00:22:47

回答

1

this questiona ||= ba || a = b的簡寫。

以及有關的@_current_user價值,如果我們假設session[:current_user_id]5,那麼&&運營商與用戶模式將返回用戶實例:

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

所以@_current_user將是用戶實例。