Ruby on rails has_one:through=>;:属于生成错误查询的\u

Ruby on rails has_one:through=>;:属于生成错误查询的\u,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,现有协会 class Job < ActiveRecord::Base belongs_to :client belongs_to :contact belongs_to :location has_one :geofence, :through => :location end class Client < ActiveRecord::Base has_many :contacts has_many :locations end class Con

现有协会

class Job < ActiveRecord::Base
  belongs_to :client
  belongs_to :contact
  belongs_to :location
  has_one :geofence, :through => :location
end

class Client < ActiveRecord::Base
  has_many :contacts
  has_many :locations
end

class Contact < ActiveRecord::Base
  belongs_to :client
end

class Location < ActiveRecord::Base
  belongs_to :client
  belongs_to :geofence
end

class Geofence < ActiveRecord::Base
  has_many :locations
end
这将产生以下错误

ActiveRecord::StatementInvalid (Mysql::Error: Unknown column 'geofences_jobs_join.location_id'
从下面的查询

SELECT `jobs`.* FROM `jobs`   INNER JOIN `clients` ON `clients`.id = `jobs`.client_id  INNER JOIN `contacts` ON `contacts`.id = `jobs`.contact_id  INNER JOIN `locations` ON `locations`.id = `jobs`.location_id  INNER JOIN `locations` geofences_jobs_join ON (`jobs`.`id` = `geofences_jobs_join`.`location_id`)  INNER JOIN `geofences` ON (`geofences`.`id` = `geofences_jobs_join`.`geofence_id`)  WHERE ...
有没有一种方法可以通过作业模型或查询的连接部分中的不同关联来解决此问题


我可以使用find_by_sql获得我需要的东西,但如果可能的话,我希望避免这种情况。

我认为为了使用
has_one:通过
关联,您的
作业
模型应该声明
has_one:location
关联,而不是相反,请参见

也就是说,您可以尝试重新定义此关联并将location_id外键从jobs表移动到locations中的job_id,或者尝试以下查询:

@jobs = Job.find(:all, :joins => [:client, :contact, { :location => :geofence }], :conditions => ['geofences.address like ?',"%#{params[:term]}%"])

在后一种情况下,您必须删除
的has\u one:through

我真的无法更改任何数据库结构这是在一个有数百万条记录的生产应用程序上。我正在给工作索引添加一个新的搜索功能。发布时的查询会产生语法错误。但我认为这可能是正确的。我相信我的问题与这个bug有关
@jobs = Job.find(:all, :joins => [:client, :contact, { :location => :geofence }], :conditions => ['geofences.address like ?',"%#{params[:term]}%"])