我在我的模型中调用另一个模型的类方法,它似乎找不到它。
详细信息
add_existing_items是Category的实例方法,我从那里调用元数据的类方法,但由于出错而失败。
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'当我从类别控制器调用类方法时,这个对Metadata类方法的调用非常好。
类别模式:
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元数据模型:
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为什么我会看到这个问题?我该怎么解决这个问题?
发布于 2014-04-08 15:54:31
问题是,当您放置行Metadata.update_or_add_metadata(new_item, true)时,默认情况下它引用的是类Mongoid::Relations::Metadata,而不是您定义的类Metadata。
因此,您需要使用范围解析操作符::为您的Metadata类提供实际路径。那就不会有任何问题了。update_or_add_metadata单例方法定义在您定义的类Metadata的单例类中,而不是在Mongoid::Relations::Metadata类的单例类上。
https://stackoverflow.com/questions/22941079
复制相似问题