从数据库中获取用户时区分 rails 中的用户和用户

Distinguishing between User and user in rails when getting a user from the database

这是我的会话控制器。我在 中更改了一行代码,但我有点不确定为什么会这样。

我查看了 classes 的定义并做了很多研究试图找出为什么 unless user.present? 不是大写 U。例如 unless User.present?

如果它是用户 class 那么它应该是要在数据库中搜索的用户,因为 User.find_by 是。

是否rails首先查看读取用户为用户的数据库,小写。

之所以这么说,是因为前面那行代码也是用user = User.from_omniauth(env["omniauth.auth"]),User也是大写的,所以rails怎么区分这两行代码都是Userclass?

def create
   user = User.from_omniauth(env["omniauth.auth"])

  unless user.present?
    user = User.find_by(email: params[:session][:email].downcase)
     if user && user.authenticate(params[:session][:password])
    log_in user
    redirect_to user_url(user)
  # Log the user in and redirect to the user's show page.
    else
     # Create an error message.
     flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end    
  else        
    log_in user
    redirect_to user_url(user)
  end
end

当你写:

user = User.from_omniauth(env["omniauth.auth"])

您正在定义一个变量 user,稍后将在您的控制器中使用。

所以,当你写:

unless user.present?

你真的在写:

unless User.from_omniauth(env["omniauth.auth"]).present?

User.from_omniauth(env["omniauth.auth"]) 从数据库中获取用户,将其存储在 user 变量中,并检查用户是否存在

此外,在您的 unless 语句中,您定义了一个 user 变量,因此它可以与第 2 行中的原始 user 变量不同的方式使用[=22] =]

ruby(和大多数语言)中的大写表示不同的意思。例如,如果您有 3 个变量:UseruserUSER,它们都是不同的。 Ruby可以区分三者,就像你的方法一样。