【问题标题】:Rails 4 sql query interpretation with mysql or sqlite3Rails 4 sql 查询解释用 mysql 或 sqlite3
【发布时间】:2015-01-28 23:16:26
【问题描述】:

我在开发中使用 sqlite,在生产中使用 mysql。

一个相同的 SQL 查询在开发模式下可以正常工作,但在生产中执行时会出错。

在 sqlite 中(有效!):

SELECT "events".* FROM "events" WHERE ("events"."id" = ? OR "events"."deadline" BETWEEN '2015-01-28 22:56:05.651383' AND '2016-01-28 22:56:05.651385'

在mysql中(不起作用):

SELECT `events`.* FROM `events` WHERE (`events`.`id` =  OR `events`.`deadline` BETWEEN '2015-01-28 22:24:10.837686' AND '2016-01-28 22:24:10.837690')

错误信息:

ERROR -- : Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'OR `events`.`deadline` BETWEEN '2015-01-28 22:24:10.837686' AND '2016-01-28 22:2' at line 1: SELECT `events`.* FROM `events` WHERE (`events`.`id` =  OR `events`.`deadline` BETWEEN '2015-01-28 22:24:10.837686' AND '2016-01-28 22:24:10.837690')

控制器动作代码

def edit
  query = Event.unscoped.where( deadline: (Time.now)..(Time.now + 1.year), id: @booking.event_id )
  @events = Event.where(query.where_values.inject(:or))
end

Mysql 错过了“?”签名,我不明白为什么。请帮忙!

【问题讨论】:

    标签: mysql sql ruby-on-rails sqlite


    【解决方案1】:

    首先,您应该在开发中使用与生产中相同的数据库。

    其次,这不是进行OR 查询的可靠方法,事实上,由于充分记录工作,它在 Rails 4.2 中不再有效。

    如果你想可靠地做ORs,那么使用Arel,即:

    e = Event.arel_table
    @events = Event.where(e[:id].eq(@booking.event_id).or(e[:deadline].in(Time.now..Time.now + 1.year)))
    

    在这篇优秀的文章中查看更多信息:http://radar.oreilly.com/2014/03/just-enough-arel.html

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 2015-11-30
      • 2017-12-09
      • 2015-09-04
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      相关资源
      最近更新 更多