我有2个班,人和会员。成员有一个名为individual_ids的方法,它返回一个ID数组,我想检索该数组中具有ID的人:
class Membership
def self.individuals
where(membershipable_type: 'individual')
end
def self.individuals_ids
individuals.pluck(:membershipable_id)
end
end
class Person
def self.individuals
Person.where(id: Membership.individuals_ids)
end
end
当我试图运行Person.individuals时,我被告知:
NameError: uninitialized constant Person::Membership
如何从上面的自我方法调用中引用Membership类,而不是认为我的意思是Person.Membership?
谢谢!
答案 0 :(得分:2)
当两个类都在同一个文件中时,您的代码可以正常工作。 Membership
类找到Person
类:
class Membership
def self.individuals
puts "Membership.individuals"
end
def self.individuals_ids
puts "Membership.individuals_ids"
end
end
class Person
def self.individuals
puts "Person.individuals"
Membership.individuals_ids
end
end
Person.individuals
#=> Person.individuals
#=> Membership.individuals_ids
这意味着您的Membership
课程不是autoloaded Rails。您可以确保在Membership
中定义了membership.rb
,并且:
membership.rb
移至app
文件夹config.autoload_paths