我有两个表方向和注册,我想对其执行联接查询。这是每个表的架构...
create_table "orientations", :force => true do |t|
t.date "class_date"
t.text "class_time"
t.integer "seats"
t.boolean "active", :default => true
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "registrations", :force => true do |t|
t.integer "orientation_id"
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "student_id"
t.string "phone"
t.string "registration_cancellation_token"
t.datetime "registration_cancelled_at"
t.boolean "checked_in", :default => false
t.boolean "cancelled", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.text "program"
end
我正在寻找的是两个日期之间所有定向的所有注册。我想出了这个...
Registration.where(Orientation.where created_at: => @start_date..@end_date)
当然,这个语法是假的,但希望它能帮助我理解我正在寻找的内容。
最佳答案
使用它来获取两个日期之间所有方向的所有注册:
Registration.joins(:orientation).where(orientations: {:class_date => @start_date..@end_date})
joins
执行INNER JOIN,过滤没有关联的行。
但是,如果您希望保留没有关联的行,那么请使用 includes
来执行LEFT OUTER JOIN
Registration.includes(:orientation).where(orientations: {:class_date => @start_date..@end_date})
关于Mysql加入rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24209239/