【问题标题】:Rails activerecord query works in sqlite not in MySqlRails activerecord 查询在 sqlite 中工作,而不是在 MySql 中
【发布时间】:2018-01-09 11:06:45
【问题描述】:

我有一个关于 sqlite 和 MariaDB 的查询问题。在开发中我使用 sqlite,但在服务器中我们使用 MariaDB。正在开发以下查询工作

Author.includes(:books, employes: :universities).where("universities.id is ? and books.year is ?",
                   @author.employes.first.universities.first.id, @book.jahr).references(:employes, :books)

但在生产中这会产生错误。当我更改为 = 时,它在服务器上工作,但在本地不会产生任何结果。

Author.includes(:books, employes: :universities).where("universities.id = ? and books.year = ?",
                   @author.employes.first.universities.first.id, @book.jahr).references(:employes, :books)

这在服务器上有效,但在本地没有结果。

编辑 如果我有这样的东西怎么办?

Author.includes(:books, employes: :universities).where("universities.id = ? and books.year = ? and employes.name like ? and id IN ?",
                       @author.employes.first.universities.first.id, @book.jahr, "%#{@employe.name}%", [1,2,3]).references(:employes, :books)

【问题讨论】:

  • 第一:在开发和生产中使用不同的数据库服务器的基本架构设计失败......第二检查生成的SQL查询。

标签: mysql ruby-on-rails sqlite activerecord mariadb


【解决方案1】:

首先正如雷蒙德所说,永远不要在开发和生产环境中使用不同的数据库。

但是现在你可以通过 ActiveRecord 的方式避免 SQL 语法错误,试试这个

Author.includes(:books, employes: :universities).where(
  universities: { id: @author.employes.first.universities.first.id },
  books: { year: @book.jahr }
).references(:employes, :books)

由于like 没有 ActiveRecord 替代品,您可以试试这个(因为like 在 MySQL 和 SQLite 中都有效,所以它会起作用)

Author.includes(:books, employes: :universities).where(
  authors: { id: [1,2,3] },
  universities: { id: @author.employes.first.universities.first.id },
  books: { year: @book.jahr }
).where('employes.name like ?', "%#{@employe.name}%").references(:employes, :books)

希望有帮助!

【讨论】:

  • 如果传递where一个Hash,则不需要使用references
  • 嗨!效果很好。你能告诉我在上面有问题的编辑中进行查询的 ActiveRecord 方式是什么吗?
猜你喜欢
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 2019-11-09
  • 2017-07-26
  • 1970-01-01
  • 2018-07-19
相关资源
最近更新 更多