gpt4 book ai didi

ruby-on-rails - 如何使用 ruby​​ 从 self 方法调用另一个方法?

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

# app/models/product.rb
class Product < ApplicationRecord
def self.method1(param1)
# Here I want to call method2 with a parameter
method2(param2)
end

def method2(param2)
# Do something
end
end

我从 Controller 调用方法 1。当我运行程序时。我收到一个错误:

method_missing(at line method2(param2))
.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0/lib/active_record/relation/batches.rb:59:in `block (2 levels) in find_each
...

最佳答案

class Product < ApplicationRecord
def self.method1(param1)
# Here I want to call method2 with a parameter
method2(param2)
end

def self.method2(param2)
# Do something
end
end

说明:第一个是类方法,第二个是实例方法。类方法不需要接收者(调用它们的对象),实例方法需要它。因此,您不能从类方法调用实例方法,因为您不知道是否有接收者(调用它的实例化对象)。

关于ruby-on-rails - 如何使用 ruby​​ 从 self 方法调用另一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41013823/

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