2016-01-10 49 views
1

我對Rails相當陌生。我一直在建立一個搜索欄,瀏覽我的所有產品。當我只通過產品名稱或描述進行搜索時,我就可以使用它。但是,如果名稱與搜索字詞匹配或符合描述,我希望將搜索字詞與要顯示的產品進行比較。在ActiveRecord中使用多個LIKE語句查詢

這是我的代碼的時刻:

if params[:q] 
    search = params[:q] 
    @products = Product.where("name LIKE ? OR description LIKE ?", "%#{search}%") 
else 
    @products = Product.all 
    end 

現在我得到一個錯誤:「綁定的錯誤數變量」

我一直在試圖谷歌的一個解決方案,但我HAVN很幸運。如果有人能幫助我,我會很感激!非常感謝。

回答

1

您需要提供兩次搜索鍵。爲每個?

search_key = "%#{search}%" 
@products = Product.where("name LIKE ? OR description LIKE ?", search_key, search_key) 
+0

啊謝謝你你這麼多!非常感謝 –

7

如果您在查詢變量具有相同的值,可以使用指定的鍵:

@products = Product.where(
    "name LIKE :search OR description LIKE :search", search: "%#{search}%" 
) 

如果他們不同:

@products = Product.where(
    "name LIKE :first_search OR description LIKE :second_search", 
    first_search: "%#{f_search}%", second_search: "%#{s_search}%" 
) 

或只使用問號:

@products = Product.where(
    "name LIKE (?) OR description LIKE (?)", "%#{f_search}%", %#{s_search}%" 
) 
相關問題