Reputation: 3250
I have a Metric class:
class Metric < ApplicationController
attr_accessor :capability, :behavior
def initialize(family_id)
@capability = 5
end
end
In a controller I do:
metrics = Metric.new(222)
Then I try to get the capability attribute with:
puts metrics.capability
but I get an error:
NoMethodError Exception: private method `capability' called for #<Metric:0xa7bb4b0 @capability=5>
What am I doing wrong???
Upvotes: 1
Views: 47
Reputation: 8132
You dont need to inherit from ApplicationController
. Stop inheriting it, it will start working.
If you want to initialise the attribute in all actions, all you have to do is this
class Metric
attr_accessor :capability, :behavior
def initialize(family_id)
@capability = 5
end
end
class ApplicationController < ActionController::Base
before_action :initialize_metric_attribute
def initialize_metric_attribute
@capability = Metric.new(10)
end
end
Edit based on comment:
You are inheriting from ApplicationController
. It should only be inherited only when you want to write some action
. For writing custom classes
,you dont need to do anything. If required you can inherit ActiveRecord::Base
.
Since, you are have initialize
method in your class metric
class, you dont even need AR
.
Why it worked ?
We have just used before_filter
callback which initialize your attribute. its Simple Ruby and Rails concept.
Upvotes: 1