2016-04-01 81 views
1

我想創建一個文檔管理系統,用戶可以按主題或按日期搜索文檔。當兩個參數都有值或兩者都爲空時,它工作正常。但是當一個人空着時,事情就會出錯。Rails + Searchkick搜索空參數

我使用params[:search]來搜索主題字段,而params[:date_filter]用於日期字段。

案例1:params[:search]爲空,params[:date_filter]存在。搜索沒有任何回報

案例2:params[:search]存在,params[:date_filter]爲空。在ArgumentError invalid date

雖然我認爲我可以修復通過將它們嵌套if條款內這些問題的搜索結果,我想尋求幫助,如果有一個更優雅的解決方案,特別是如果我考慮更多的參數,將意味着更多的if條款。

下面是我用在我的控制器代碼:

if params[:search].present? || params[:date_filter].present? 

    @ingoing = Document.search(
    params[:search], 
    where: { 
     outgoing: false, 
     date: { 
     gte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').beginning_of_day, 
     lte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').end_of_day 
     } 
    }, 
    order: {created_at: :desc}) 
    @outgoing = Document.search(
    params[:search], 
    where: { 
     outgoing: true, 
     date: { 
     gte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').beginning_of_day, 
     lte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').end_of_day 
     } 
    }, 
    order: {created_at: :desc}) 
else 
    @documents = Document.all 
    @ingoing = @documents.where(outgoing: false).order('created_at desc') 
    @outgoing = @documents.where(outgoing: true).order('created_at desc') 
end 

更新: 使用的@ CupawnTae的代碼來解決問題

search = params[:search].present? ? params[:search] : "*" 
#where = {order: {created_at: :desc}} 
#This kept throwing an unknown where operand error so I changed it 
#Also can't put misspellings: false here since it keeps returning empty results 
where = {} 

if params[:date_filter].present? 
    where[:date] = { 
    gte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').beginning_of_day, 
    lte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').end_of_day 
    } 
end 

#Put the order here, as well as the misspelling option since putting it at the top returned empty results. 
@ingoing = Document.search(search, where: where.merge(:outgoing => false), order: {created_at: :desc}, misspellings: false) 
@outgoing = Document.search(search, where: where.merge(:outgoing => true), order: {created_at: :desc}, misspellings: false) 

回答

0

修改後的版本怎麼樣這樣的事情?

search = params[:search].present? ? params[:search] : "*" 
where = {order: {created_at: :desc}} 

if params[:date_filter].present? 
    where[:date] = { 
    gte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').beginning_of_day, 
    lte: DateTime.strptime(params[:date_filter], '%m/%d/%Y %l:%M %p').end_of_day 
    } 
end 

@ingoing = Document.search search, where: where.merge(:outgoing => false) 
@outgoing = Document.search search, where: where.merge(:outgoing => true) 
+0

謝謝,但現在它忽略了我的日期輸入,並且出於某種原因'@ ingoing'和'@ outgoing'變量輸出了相同的結果。 –

+0

哎呀,對不起,沒有searchkick在這裏測試 - 我錯過了'在哪裏:'在搜索參數 - 嘗試更新代碼 – CupawnTae

+0

非常感謝!我不得不修改一些小部分,因爲他們拋出錯誤或產生空白的結果,但它最終奏效。 –