Activerecord加入has_many:through

时间:2010-06-29 14:14:37

标签: ruby-on-rails

ActiveRecord::StatementInvalid: 
Mysql::Error: Unknown column 'schedules.id' in 'on clause': 
SELECT `schedules`.* FROM `schedules`   INNER JOIN `shops` ON 
(`schedules`.`id` = `shops`.`shop_id`)  INNER JOIN `areas` ON 
(`areas`.`id` = `shops`.`area_id`)

正确的sql语句应该包含'schedule'.'shop_id'='shops'。'id'而不是'schedules'。'id'='shops'。'shop_id'。 为了实现这一目标,我可以在模型中做些什么改变?

以下是这三个类的模型:

class Area < ActiveRecord::Base  
  has_many :shops  
  has_many :schedules, :through => :shop  
end  

class Schedule < ActiveRecord::Base  
  belongs_to :shop  
  has_many :areas, :through => :shop  
end  

class Shop < ActiveRecord::Base  
  belongs_to :area # foreign key - area_id  
  has_many :schedule  
end

创建该sql命令的命令:     Schedule.find:all,:joins =&gt; [:shop,:areas]

在db / schema.rb中我有:

create_table "areas", :force => true do |t| 
  t.string   "campus"
  t.datetime "created_at"
  t.datetime "updated_at"
end 

create_table "shops", :force => true do |t|
  t.integer  "area_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "schedules", :force => true do |t|
  t.integer  "shop_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

1 个答案:

答案 0 :(得分:0)

我认为你的查询应该使用:include选项来指定

Schedule.find :all, :include => [:shops, :areas]

:join选项用于指定连接逻辑,例如“INNER JOIN ...”