如何用ruby从self方法调用另一个方法?

s_z*_*ang 6 ruby activerecord ruby-on-rails

# 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
Run Code Online (Sandbox Code Playgroud)

我从控制器调用method1.当我运行程序时.我收到一个错误:

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
...
Run Code Online (Sandbox Code Playgroud)

Urs*_*sus 8

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
Run Code Online (Sandbox Code Playgroud)

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