ruby-on-rails - has_one :through => :belongs_to produces bad query

标签 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 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 关联,而不是反过来,参见 this example .

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

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

在后一种情况下,您必须删除 has_one :through

关于ruby-on-rails - has_one :through => :belongs_to produces bad query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12144870/

相关文章:

ruby-on-rails - 我如何知道Rails代码是通过rake还是脚本/生成来运行?

mysql - ruby ActiveRecord : Insert to parent and child tables in single commit

ruby - NameError:未初始化的常量 ActiveRecord::Migrator::Zlib

ruby-on-rails - 使用 ActiveRecord 和 Rails 将数据插入 postgresql 数据库出现此错误 : RuntimeError: ERROR C22003 Minteger o

ruby-on-rails-4 - Rails - 在迁移期间将表保留在 structure.sql 之外

ruby-on-rails - Rails Query组并选择返回由另一个属性分组的ID数组?

ruby-on-rails - 使用 Nokogiri 解析具有多个值的节点的 XML

mysql - 无法迁移 .csv 文件

mysql - 尝试连接到 AWS MySQL 实例时 ActiveRecord NoDatabaseError

ruby-on-rails - 为什么 Ruby on Rails 使用 http ://0. 0.0.0 :3000 instead of http://localhost:3000?