Ruby on rails 在名称空间模型上有许多错误

Ruby on rails 在名称空间模型上有许多错误,ruby-on-rails,Ruby On Rails,我有以下几点 class Service < ActiveRecord::Base has_many :service_testimonials, class_name: 'Service::Testimonial', dependent: :destroy has_many :testimonials, through: :service_testimonials end class Service::Testimonial < ActiveRecord::Base

我有以下几点

class Service < ActiveRecord::Base
  has_many :service_testimonials, class_name: 'Service::Testimonial', dependent: :destroy
  has_many :testimonials, through: :service_testimonials
end

class Service::Testimonial < ActiveRecord::Base
  belongs_to :service
  belongs_to :testimonial
end

class Testimonial < ActiveRecord::Base

  has_many :service_testimonials, class_name: 'Service::Testimonial', dependent: :destroy
  has_many :services, through: :service_testimonials
end
类服务
但是如果我做了
Service.first.estimationals
sql是
选择“Service\u estimationals”。*从“Service\u estimationals”内部连接“Service\u estimationals”“Service\u estimationals\u JOIN”在“Service\u estimationals”“id”=“Service\u estimationals\u estimationals\u JOIN”中的“Service\u estimationals\u JOIN”。“服务id”=$1[[“服务id”,1]]


因此,它返回一个
服务::认证
的集合,而不是
认证
,将
类名
添加到through没有帮助。我可以让它工作吗?或者我只需要重命名我的模型吗?

您需要在
服务::认证
类中进行更改:

class Service::Testimonial < ActiveRecord::Base
  belongs_to :service, class_name: '::Service'
  belongs_to :testimonial, class_name: '::Testimonial'
end
class服务::推荐

那些
class\u name
s是必须的,因为Rails是在同一名称空间中查找类的。因此,例如,声明
属于:service
将被解释为
属于:service,class\u name:'service::service'
,这显然不是您的意图。

当您添加
class\u name:
(关于所属:推荐)您是否使用了
::Certificial'
来确保您针对的是顶级
Certificial
类?japed我已经更新了我的答案。它现在可以正常工作了。没有模块
服务
,该类正在
服务::Certificial
中使用名称空间-没有说这不会引起问题,因为它有时会引起问题(类和模块加载常量略有不同)但只是澄清没有模块
服务
(至少在给出的示例中没有)@Shadwell谢谢你的提醒!你是对的:在这个设置中没有
服务
模块。但我认为这应该被视为一种不好的做法。如果我们在
服务
类之前定义了
服务::一个
类,它会创建
服务
模块,那么
服务
类定义就会失败。我明白为什么了这可能被认为是一种不好的做法,我这样做的主要原因是整理我的模型文件夹。我想我会取消它们的名称,只是让它们变得不那么有条理。这似乎造成了太多的问题。编辑你的答案,就像@Shadwell说的那样,我需要使用顶级的
推荐信
。谢谢你的帮助lp