我有以下
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.testimonials
,那么sql是SELECT "service_testimonials".* FROM "service_testimonials" INNER JOIN "service_testimonials" "service_testimonials_testimonials_join" ON "service_testimonials"."id" = "service_testimonials_testimonials_join"."testimonial_id" WHERE "service_testimonials_testimonials_join"."service_id" = $1 [["service_id", 1]]
因此,它会返回Service::Testimonial
而不是Testimonial
的集合,向通过添加class_name
无效。我可以让这个工作吗?或者我只是需要重命名我的模型?
答案 0 :(得分:0)
您需要在Service::Testimonial
课程中进行更改:
class Service::Testimonial < ActiveRecord::Base
belongs_to :service, class_name: '::Service'
belongs_to :testimonial, class_name: '::Testimonial'
end
那些class_name
是强制性的,因为Rails assumes,您正在寻找同一名称空间中的类。因此,例如声明belongs_to :service
将被解释为belongs_to :service, class_name: 'Service::Service'
,这显然不是您的意图。