问题
I have two models in a namespace, a service and an instructor, both which have a many to many relationship with each other, defined through a 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
In the scope of_service, I want of_service to return all instructors that are associated with a service.
However, when running this scope, I get an error:
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 "services"."id" = 107 LIMIT 1
Where it seems to be going wrong is that its joining a table called instructors_services (that table doesnt exist), ignoring the namespace in the related model. It should be joining a table called scheduling_instructors_services, which is consistent with the namespace.
回答1:
Try adding :join_table => 'scheduling_instructors_services' to your relations like this:
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'
Also, shouldn't it be
.where('instructors_services.id' => service_id)
instead of
.where(:services => {:id => service_id})
来源:https://stackoverflow.com/questions/16442794/in-rails-activerecord-joins-does-not-work-with-has-and-belongs-to-many-in-names