rails 中的会话和 user_id

roo*_*nie 3 session ruby-on-rails userid

我在理解 Rails 的会话和身份验证时遇到了很多麻烦。所以基本上,我尝试根据书中的教程设置基于 user_id 的会话。这是我的 session_controller.rb 文件中的 create 方法:

def create
if user = User.authenticate(params[:email], params[:password])
  session[:id] = user.id
  redirect_to root_path, :notice => 'Logged in successfully'
else
  flash.now[:alert] = "Invalid login/password combination"
  render :action => 'new'
end
Run Code Online (Sandbox Code Playgroud)

结尾

但是,当我尝试在 application_controller.rb 文件中定义 current_user 方法时,它要求我根据 user_id 引用会话:

def current_user
  return unless session[:user_id]
  @current_user = User.find_by_id(session[:user_id])
end
Run Code Online (Sandbox Code Playgroud)

这让我感到困惑 - user_id 是每个食谱(相当于我的应用程序中的文章或帖子)的一个属性,它与用户创建了 has_one 关系。我的应用程序中没有其他地方定义了 user_id。所以 user_id 不应该是用户的属性,对吗?

为了澄清起见,我已经从 rails 控制台列出了 User 对象和 Recipe 对象的参数:

    2.0.0-p598 :019 >   Recipe 
    => Recipe(id: integer, title: string, body: text, published_at:    
    datetime, created_at: datetime, updated_at: datetime, user_id: 
    integer, photo_of_recipe_file_name: string, 
    photo_of_recipe_content_type: string, photo_of_recipe_file_size:   
    integer, photo_of_recipe_updated_at: datetime)

    2.0.0-p598 :020 > User
    => User(id: integer, email: string, hashed_password: string,     
    created_at: datetime, updated_at: datetime, username: string)
Run Code Online (Sandbox Code Playgroud)

PGi*_*ill 7

在您的创建方法中,它应该是

session[:user_id] = user.id
Run Code Online (Sandbox Code Playgroud)

您正在:user_id会话哈希中设置一个密钥并将经过身份验证的用户的 ID 存储user.id在其中以供以后使用

键名可以是任何东西