0

次のように私はApplicationRecordモデルを持っている:Railsの5モデルが親のメソッドを継承していない

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

    def hello_world 
    return "helllloo" 
    end 
end 

をし、次のように私はInstanceモデルを持っている:

class Instance < ApplicationRecord 

end 

それから私は、コントローラが実行しようとしていますhello_worldですが、hello_worldメソッドが利用できないという次のエラーが発生しています。

コントローラ

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 

エラー

{ 
    "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'" 
     } 
    ],..... 

それがメソッドを継承していない理由を任意のアイデア?

**注:**私はAPIモードでアプリを実行しています。ここで言及する

答えて

1

一つのポイントは、インスタンスメソッドhello_worldさであり、あなたではなく、インスタンスのクラスにそれを呼び出している

解決方法1:

変更クラスメソッドへのメソッド

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

    def self.hello_world 
    return "helllloo" 
    end 
end 

および

Instance.hello_world 
#=> "helllloo" 

解決方法2:

コールインスタンス上のメソッド

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

    def hello_world 
    return "helllloo" 
    end 
end 

Instance.new.hello_world 
#=> "helllloo" 

# OR 

instance = Instance.new 
instance.hello_world 
#=> "helllloo" 
関連する問題