Activerecord join with has_many :through
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`)
The correct sql statement should include 'schedules'.'shop_id' = 'shops'.'id' instead of 'schedules'.'id' = 'shops'.'shop_id'. What can I change in my models to make this happen?
Here are the models for these three classes:
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
The command that created that sql command: Schedule.find :all, :joins => [:shop, :areas]
In db/schema.rb I have:
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"
开发者_如何学JAVA 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
I think your query should be specified using the :include option like so
Schedule.find :all, :include => [:shops, :areas]
The :join option is for specifying join logic such as "INNER JOIN ..."
精彩评论