Reputation: 151
I am calling a class method of another model in my model and it seems to not find it.
Details
add_existing_items
is the instance method of Category
from where I make a call to class method of Metadata and this fails with the error.
Caught exception : NoMethodError : undefined method `update_or_add_metadata' for Mongoid::Relations::Metadata:Class
/Users/anil20787/workspace/repos/anil_reps/metadata_favorite/app/models/category.rb:36:in `block in add_existing_items'
This call to class method of Metadata
works absolutely fine when I call it from my Category controller.
Category model:
class Category
include Mongoid::Document
belongs_to :catalog
has_many :category_items
# fields go here
# validations go here
def add_existing_items(inputs)
if inputs[:category_item_ids] && inputs[:category_item_ids].kind_of?(Array)
inputs[:category_item_ids].each do |category_item_id|
category_item = CategoryItem.find(category_item_id)
new_item = category_item.dup
new_item.category = self
new_item.save!
# 'new_item' document gets saved successfully
# But the below call to class method of another class fails! Why?
Metadata.update_or_add_metadata(new_item, true)
end
end
end
end
Metadata model:
class Metadata
include Mongoid::Document
include Mongoid::Timestamps
# fields go here
# validations go here
belongs_to :outlet
# instance methods go here
class << self
def update_or_add_metadata(item, create_new_boolean)
# do the updating work
end
end
end
Why am I seeing this problem? How do I resolve this?
Upvotes: 1
Views: 810
Reputation: 118271
The problem is, when you put the line Metadata.update_or_add_metadata(new_item, true)
, it refers to the class Mongoid::Relations::Metadata
by default, not the class Metadata
you have defined.
Thus you need to give actual path to your Metadata
class using scope resolution operator ::
. Then there will not be any problem. update_or_add_metadata
singleton method defined in the singleton class of the class Metadata
you defined, not on the singleton class of Mongoid::Relations::Metadata
class.
Upvotes: 2