2017-08-02 49 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