0

du parent que j'ai le modèle ApplicationRecord comme suit:Rails 5 Modèle non héritant méthodes

class ApplicationRecord < ActiveRecord::Base 
    self.abstract_class = true 

    def hello_world 
    return "helllloo" 
    end 
end 

et j'ai modèle Instance comme suit:

class Instance < ApplicationRecord 

end 

Ensuite, je dois le contrôleur essayes d'exécuter le hello_world, mais il lance l'erreur suivante en disant que la méthode hello_world n'est pas disponible.

Contrôleur

class InstancesController < ApplicationController 
    before_action :set_instance, only: [:show, :update, :destroy] 

    # GET /instances 
    def index 
    @instances = Instance.all 
    return render(:json => {:instances => @instances, :hi_message => Instance.hello_world}) 
    end 
end 

Erreur

{ 
    "status": 500, 
    "error": "Internal Server Error", 
    "exception": "#<NoMethodError: undefined method `hello_world' for #<Class:0x00000009b3d4a0>>", 
    "traces": { 
    "Application Trace": [ 
     { 
     "id": 1, 
     "trace": "app/controllers/instances_controller.rb:7:in `index'" 
     } 
    ],..... 

Toute idée pourquoi il ne héritant des méthodes?

** Remarque: ** J'utilise l'application en mode API.

Répondre

1

Un point à mentionner ici est hello_world est la méthode d'instance et vous appelez sur une classe au lieu d'exemple

Solution 1:

changer la méthode de méthode de classe

class ApplicationRecord < ActiveRecord::Base 
    self.abstract_class = true 

    def self.hello_world 
    return "helllloo" 
    end 
end 

et

Instance.hello_world 
#=> "helllloo" 

Solution 2:

Appelez la méthode sur l'instance

class ApplicationRecord < ActiveRecord::Base 
    self.abstract_class = true 

    def hello_world 
    return "helllloo" 
    end 
end 

et

Instance.new.hello_world 
#=> "helllloo" 

# OR 

instance = Instance.new 
instance.hello_world 
#=> "helllloo"