1

我正在使用rails3-jquery-autocomplete gem在我的rails 3應用程序中自動填充表單中的字段(產品)。用戶可以輸入產品名稱或產品代碼,這兩個產品表格都是字符串列。 一切正常本地,但在Heroku上與標準的500 Heroku的錯誤Ajax請求崩潰:Rails Autocomplete在本地工作,但不在Heroku上,可能是MySQL/Postgre問題

We're sorry, but something went wrong (500) 

我覺得這可能是一個postgre/SQL的問題 - 我用mysql本地發展,但是Heroku的運行在postgre SQL數據庫,我在由AJAX自動完成的請求獲得了卡列斯的功能做以下查詢:

def get_autocomplete_items(parameters) 
    items = Product.select("DISTINCT CONCAT_WS(' ', product_code, title, id) AS full_name, product_code, title, id").where(["CONCAT_WS(' ', product_code, title) LIKE ?", "%#{parameters[:term]}%"]) 
    end 

本地,這將返回我的JSON格式的數組,包括所有匹配produc_ids和名稱:

[{"id":"9","label":"xt-pnt-dress_45 - Catherine Malandrino","value":"xt-pnt-dress_45 - Catherine Malandrino"}, ... ] 

如果有人有一個想法如何改變它符合heroku或任何其他想法的查詢,我會非常感激。謝謝。

回答

3

Heroku使用PostgreSQL 8.3 for shared databases and 9.0 for dedicated databasesversion 8.3version 9.0都沒有concat_ws函數,該函數僅在version 9.1+中可用。

你可以手工雖然在連接字符串:

items = Product.select("DISTINCT product_code || ' ' || title || ' ' || id AS full_name, product_code, title, id").where(["product_code || ' ' || title LIKE ?", "%#{parameters[:term]}%"]) 

只要將工作爲無的product_codetitleid是NULL。如果你可能有NULL,那麼你可以把它們包裝成COALESCE(例如COALESCE(product_code || ' ', ''))把它們變成空字符串。

或者,你可以照顧full_name的紅寶石:

def full_name 
    [product_code, title, id].reject(&:blank?).join(' ') 
end 

,並有等的單獨生成列或檢查雙方柱與LIKE:

where('product_code LIKE ? OR title LIKE ?', "%#{parameters[:term]}%", "%#{parameters[:term]}%") 
where('produce_code LIKE :pat OR title LIKE :pat', :pat => "%#{parameters[:term]}%") 

此外,你應該請注意,MySQL的LIKE不區分大小寫,但PostgreSQL的不是這樣,您可能想要將所有內容都排除在外以避免混淆:

where('LOWER(product_code) LIKE :pat OR LOWER(title) LIKE :pat', :pat => "%#{parameters[:term].downcase}%") 
where('LOWER(product_code) LIKE :pat OR LOWER(title) LIKE :pat', :pat => "%#{parameters[:term].downcase}%") 

由於|| is a logical-OR in MySQL,加入Ruby中的三個字符串(即def full_name)和檢查product_codetitle與單獨downcased LIKE可能是最乾淨的便攜式解決方案。

將您的開發環境切換到PostgreSQL也是一個好主意,與您的部署環境匹配的版本也是一個好主意。還有其他的差異會造成麻煩。

+0

感謝這個詳細的答案 - 它不僅有效,而且還提供了很多有關該主題的背景信息以及最佳實踐的一些提示 - 超級! – tmaximini 2011-12-28 15:03:26

+0

我介紹的一件事情是,如果我製作一個虛擬屬性連接字符串標題和產品代碼,例如'full_name',我想搜索它,我得到一個'ActiveRecord :: StatementInvalid:Mysql :: Error':'where子句'中的未知列'full_name':SELECT'products'。* FROM'products' WHERE(LOWER(full_name )LIKE'%ib%')'錯誤.. – tmaximini 2011-12-29 13:05:33

+0

@frank:另一個選擇是將可搜索的列連接在一起(這裏使用'before_save'回調),然後你可以搜索那個堆。 – 2011-12-29 19:05:08

相關問題