Reputation: 3299
I have the ApplicationRecord
model as follows:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def hello_world
return "helllloo"
end
end
and I have Instance
model as follows:
class Instance < ApplicationRecord
end
Then I have the controller trying to run the hello_world
, but it's throwing the following error saying hello_world
method is not available.
Controller
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
Error
{
"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'"
}
],.....
Any idea why it's not inheriting the methods?
**Note: ** I am running the app in API mode.
Upvotes: 1
Views: 708
Reputation: 23661
One point to mention here is hello_world
is instance method and you are calling it on a class instead of instance
Solution 1:
Change the method to class method
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.hello_world
return "helllloo"
end
end
and
Instance.hello_world
#=> "helllloo"
Solution 2:
Call the method on instance
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def hello_world
return "helllloo"
end
end
and
Instance.new.hello_world
#=> "helllloo"
# OR
instance = Instance.new
instance.hello_world
#=> "helllloo"
Upvotes: 2