Reputation: 177
I have a model with the following method
class Legacy::Retailer < ActiveRecord::Base
belongs_to :retailers
self.table_name = 'orim_retailers'
def retailer_options
retailers = Array.new
self.display_name.each do |names|
retailers << names
end
end
end
When I try to call this method from the controller as
@retailer_options = Legacy::Retailer.retailer_options
I get a method an undefined method error. I'm not sure what I'm doing wrong.
Upvotes: 0
Views: 719
Reputation: 1172
The method retailer_options was defined as an instance method, and you are calling a class method. Take a look at the following code:
class Foo
def self.bar
puts 'class method'
end
def baz
puts 'instance method'
end
end
If you call:
Foo.bar # => "class method"
Foo.baz # => NoMethodError: undefined method ‘baz’ for Foo:Class
And for the instance method:
Foo.new.baz # => instance method
Foo.new.bar # => NoMethodError: undefined method ‘bar’ for #<Foo:0x1e820>
Hope it's more clear now
Upvotes: 1
Reputation: 52377
Because you defined an instance method, not a class method.
To be able to call
Legacy::Retailer.retailer_options
you should define a class method:
def self.retailer_options # note self here
retailers = Array.new
self.display_name.each do |names|
retailers << names
end
end
And if you've meant to call this method on instances, not class itself, you should be able to do the following:
Legacy::Retailer.new.retailer_options
Upvotes: 4
Reputation: 5489
you've defined an instance method but you're calling it as a class method.
@retailer = Legacy::Retailer.new
@retailer.retailer_options
will work
Upvotes: 0