2017-08-02 54 views
0

我有一个SQLite和MariaDB的查询问题。在开发中,我使用sqlite,但在服务器中我们使用MariaDB。在开发以下查询作品Rails的activerecord查询工作在sqlite不在MySql

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) 
+1

第一:在开发和生产中使用不同数据库服务器的基本体系结构设计失败...其次检查生成的SQL查询。 –

回答

2

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

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

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

由于没有ActiveRecord的替代方案为like,你可以试试这个(它的工作,因为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) 

希望帮助!

+2

如果通过'哪里'哈希,它不需要使用'参考' –

+0

嗨!它效果很好。你能告诉我什么是在上面的编辑问题中执行查询的ActiveRecord方式? – asdfkjasdfjk