gpt4 book ai didi

ruby-on-rails - self 在 ruby​​ on rails 中做什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:01:34 25 4
gpt4 key购买 nike

我在 railcasts 上只是练习一些 rails 并且遇到了一些我试图理解的东西。

我不明白 authenticate 方法中的“self”在做什么。所以我删除了它并测试了我的应用程序的登录以查看它是否会显示错误并且确实如此:

error:

**NoMethodError in SessionsController#create
undefined method `authenticate' for #<Class:0x00000102cb9000**>

如果有人能准确解释“ self ”在做什么,我将不胜感激。我试图弄清楚到底发生了什么,但无法理解它。

方法在模型中定义并在 sessions_controller 中调用..我一直在不断删除我的应用程序,并从头开始以掌握它的窍门,每次我重新开始时,很多事情对我来说都很有意义,但我坚持“ self ”。

我就是那种喜欢理解为什么会起作用的人。

Controller :

 def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_path, :notice => "Logged In"
else
flash.now.alert = "Invalid credentials"
render "new"
end
end

型号:

 def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end

最佳答案

这是一个基本的 ruby​​ 问题。在这种情况下,self 用于定义类方法。

    class MyClass
def instance_method
puts "instance method"
end

def self.class_method
puts "class method"
end
end

像这样使用:

    instance = MyClass.new
instance.instance_method

或者:

    MyClass.class_method

希望这能让事情变得更清楚一些。另请参阅:http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

关于ruby-on-rails - self 在 ruby​​ on rails 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7520444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com