Mysql加入rails

标签 mysql sql ruby-on-rails

我有两个表方向和注册,我想对其执行联接查询。这是每个表的架构...

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/

相关文章:

java - 在测试环境中使用 MariaDB,在生产环境中使用 sql server,如何同时使用一个选择? - Java, Spring

sql - 如何按顺序将两个具有相同行数的表连接在一起

javascript - 多个用户的帖子无法正确加载

jQuery 匹配设置为字符串

mysql - 为什么mysql select结果显示 "#REF!"而不是 "NULL"

mysql - 将表字段 1 更新为字段 2,其中字段 1 等于字段 3

php - 有没有一个网站可以简单地输出php和mysql的最新稳定版本号?

sql - 通过连接表查找相似用户的算法

带有分组依据的子查询的 MySQL UPDATE

ruby-on-rails - Rails 允许用户设置默认值