3

我在命名空间中有两个模型,一个服务和一个指导员,它们彼此之间具有多对多关系,通过 has_and_belongs_to_many 定义:

class Scheduling::Service < ActiveRecord::Base

  has_and_belongs_to_many :instructors
end

class Scheduling::Instructor < ActiveRecord::Base
  attr_accessible :first_name, :last_name
  has_many :instructor_availabilities

  scope :of_service, lambda { |service_id| joins(:services).where(:services => {:id => service_id})}

  has_and_belongs_to_many :services, :class_name => "Scheduling::Service"
end

在 of_service 范围内,我希望 of_service 返回与服务关联的所有讲师。

但是,在运行此范围时,出现错误:

ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table "services" LINE 1: ...."id" = "instructors_services"."service_id" WHERE "services"... ^ : SELECT “scheduling_instructors”。* FROM “scheduling_instructors” INNER JOIN “instructors_services” ON “instructors_services”。“instructor_id” = “scheduling_instructors”。“id” INNER JOIN “scheduling_services” ON “scheduling_services”。“id” = “instructors_services”。“service_id” " WHERE "服务"."id" = 107 LIMIT 1

它似乎出错的地方是它加入了一个名为instructors_services 的表(该表不存在),忽略了相关模型中的命名空间。它应该加入一个名为 scheduling_instructors_services 的表,该表与命名空间一致。

4

1 回答 1

4

尝试:join_table => 'scheduling_instructors_services'像这样添加到您的关系中:

has_and_belongs_to_many :instructors, :class_name => "Scheduling::Instructor", :join_table => 'scheduling_instructors_services'
has_and_belongs_to_many :services, :class_name => "Scheduling:: Service", :join_table => 'scheduling_instructors_services'

还有,不应该

.where('instructors_services.id' => service_id)

代替

.where(:services => {:id => service_id})

于 2013-05-08T14:08:06.347 回答