class Program < ActiveRecord::Base
belongs_to :channel
end
class ProgramSchedule < ActiveRecord::Base
belongs_to :program
end
Schema.rb
create_table "channels", :force => true do |t|
t.string "site"
t.string "name"
t.string "icon"
t.string "type"
t.string "country"
t.integer "ordertab"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "homepage"
end
add_index "channels", ["site"], :name => "index_channels_on_site", :unique => true
create_table "program_schedules", :force => true do |t|
t.integer "program_id"
t.datetime "start"
t.datetime "stop"
end
add_index "program_schedules", ["program_id"], :name => "index_program_schedules_on_program_id"
create_table "programs", :force => true do |t|
t.integer "channel_id"
t.string "title"
t.string "subtitle"
t.text "description"
t.float "official_rating"
t.float "rating"
t.string "type"
t.integer "likes"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "programs", ["channel_id"], :name => "index_programs_on_channel_id"
add_index "programs", ["title", "channel_id"], :name => "index_programs_on_title_and_channel_id", :unique => true
我必须运行此SQL查询:
DELETE program_schedules.*
FROM program_schedules INNER JOIN programs ON program_schedules.pid = programs.id
WHERE programs.channel_id = '1'
AND (
program_schedules.start >= '2011-12-12'
AND program_schedules.start <= '2011-12-12'
)
Ruby on Rails中的......
ProgramSchedule.joins(:program).delete_all(
:start => (dates_array.min)..(dates_array.max),
:programs => {:channel_id => 1}
)
错误:(ActiveRecord :: StatementInvalid) /Library/Ruby/Gems/1.8/gems/activerecord-3.1.3/lib/active_record/connection_adapters/mysql2_adapter.rb:283:in`query':
Mysql2::Error: Unknown column 'programs.channel_id' in 'where clause':
DELETE FROM `program_schedules` WHERE `programs`.`channel_id` = 1 AND (`program_schedules`.`start` BETWEEN '2011-12-09 23:00:00' AND
'2011-12-10 22:20:00')
答案 0 :(得分:0)
您的表实际上是programs
(带有尾随s)还是program
(没有)。
因为在您的手写查询中,您引用的是没有's'的表,并且在您的Rails查询中使用...
答案 1 :(得分:0)
生成的SQL似乎并没有真正执行连接。尝试重构查询,如下所示:
ProgramSchedule.joins(:program)
.where(start: (dates_array.min) ..(dates_array.max)
.where(programs: {channel_id: 1})
.delete_all
你不必使用2 where子句,我只是这样做是为了让我的连接条件与原始表格中的条件分开。