Pooja Mokariya
Pooja Mokariya

Reputation: 2120

Need to call self.method in another method with ruby

app/models/product.rb

    class Product < ApplicationRecord
      def methode1.1
        # Do something
      end
      def method1
        # Do something
        methode1.1
      end
      def self.method2
        # Do something
        method1
      end
    end

in controller

def Method_4
  # Do something
  Product.method2
  # Do something
end

I call method2 from controller. When I run the program. I got an error:

undefined local variable or method methode1 '' for class

Upvotes: 2

Views: 177

Answers (1)

mrzasa
mrzasa

Reputation: 23307

You call a class method Product.method2 and it tries to call an instance method method1. In order to do that, you need to find or initialize an instance of a model, e.g.:

  # initialize
  def self.method2
    # Do something
    new.method1
  end

or

  # find
  def self.method2
    # Do something
    find_by(attr1: val1, attr2: val2).method1
  end

Upvotes: 1

Related Questions