2016-07-24 54 views
-1

情景是,我想獲取2個案例的所有時間片。無法重構代碼軌4查詢

  1. 如果看門人是真正的查詢將是相同的

  2. 如果門衛是假的話,需要在查詢中添加參數

因此,其相同的查詢幾乎是意志對這兩種情況都很少修改。

下面是查詢和代碼:

def self.latest_pickup_date current_zone,doorman 
    if doorman 
     latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone).order(:slot_date).last 
    else 
     latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone, doorman_type: "none").order(:slot_date).last 
    end 
    latest_timeslot.nil? ? Date.current : latest_timeslot.slot_date 
    end 

我想修改我的代碼和查詢的方式使用空的方法。

我不想在這兩種情況下寫這些查詢兩次。我需要使用代碼實踐的更好的解決方案。或者如果我正確地做這件事,你也可以提供建議。

另外還需要好的專業代碼實踐和代碼重構,以及任何人都可以提供幫助。

+0

你的問題的標題是_unable到refactor_,爲什麼是你無法重構?你知道http://codereview.stackexchange.com/嗎? –

+0

@Зелёный我沒有那麼多好的知識,而且我的專業知識有限,所以我發佈了專家解答。我的意圖不是隻得到答案。我也可以自己做。 以及我不知道codereview.stackexchange.com – LearningROR

+0

您應該將此問題發佈到http://codereview.stackexchange.com/ –

回答

2

你可以做一個where在現有的查詢,添加附加條件,並且如果使用try的查詢爲空

def self.latest_pickup_date current_zone,doormam 
    latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone).order(:slot_date) 
    latest_timeslot = latest_timeslot.where(doorman_type: 'none') unless doorman 
    latest_timeslot.last.try(:slot_date) || Date.current 
end 
+0

去這個方法。這是最乾淨的解決方案 –

+0

這是代碼做了兩個查詢,雖然它只能做一個,也'嘗試'這是一個不好的做法。 –

+0

我也在想同樣的事情。它看起來像2個查詢。反正它真的很好。 爲什麼'嘗試'是不好的做法? – LearningROR

1

你可以請檢查下面的重構代碼,讓我知道你是否喜歡這種方法。

def self.latest_pickup_date current_zone,doorman 
    filters = {dropoff_slots: '-1', zone_id: current_zone} 
    filters[:doorman_type] = "none" unless doorman 

    latest_timeslot = Timeslot.where(filters).order(:slot_date).last 

    latest_timeslot.nil? ? Date.current : latest_timeslot.slot_date 
end 
+0

您是否可以在代碼中添加註釋?謝謝btw。看起來不錯。 – LearningROR

+0

基本上where子句接受字典。因此,您可以分別傳遞過濾器列和值,也可以傳遞字典。在字典中,鍵應該是列名稱,值應該是您想要用於過濾的值。這就是我在這裏做, 過濾器= {dropoff_slots: '-1',zone_id:current_zone}#前兩個字段 過濾器[:doorman_type] = 「無」,除非門衛#The可選字段 latest_timeslot =時隙.where(filters).order(:slot_date).last#過濾器 當doorman不爲空時,您將doorman_type添加到字典中。 – Pragash

+0

好吧,你可以添加鏈接來閱讀更多關於過濾器? 加上一件事:'filters [:doorman_type]'這段代碼是在過濾器中添加另一個鍵?我對嗎?我的意思是在我們的詞典中加入了其他兩個關鍵詞'filters [:doorman_type]'? – LearningROR