has_one :through => :belongs_to 产生错误的查询



现有关联

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

在试图从各种表格中搜索字段时,我做了这样的

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

其产生以下错误

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 :through关联,您的Job模型应该声明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_one :through

相关内容

最新更新