Rails 5 Model不继承父方法

时间:2017-05-18 18:13:33

标签: ruby-on-rails inheritance abstract-class ruby-on-rails-5

我的ApplicationRecord模型如下:

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 个答案:

答案 0 :(得分:2)

这里要提到的一点是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"