2015-10-15 53 views
0

我試圖創建一個作用域來返回落在特定範圍和日期之間的所有記錄。使用AND條件和之間的Rails作用域

我有完成此方法,但我試圖重構它。

原始的方法:

def self.find_by_time facility_id, start_time_string 
    day_of_week = start_time_string.to_date.wday 
    start_time= start_time_string.to_datetime.strftime("%H:%M") 
    self 
    .where("facility_id = ? AND (? BETWEEN start_day AND end_day) AND (? BETWEEN start_time AND end_time)", 
    facility_id, day_of_week, start_time) 
    end 

這工作得很好,但我不喜歡這裏的使用SQL,我想使用範圍和squeel把它清理乾淨。我還希望直接傳遞Facility對象而不是僅僅傳入id。

這就是我想:

scope :within_weekday, -> (weekday) {where {start_day <= weekday} & {end_day >= weekday}} 
    scope :within_time, -> (time) {where {start_time <= time} & {end_time >= time}} 

    def self.find_by_time facility, start_time 
    day_of_week = start_time_string.to_date.wday 
    start_time= start_time_string.to_datetime.strftime("%H:%M") 
    self.find_by(facility: facility).within_date(day_of_week).within_time(start_time).first 
    end 

一些錯誤,我越來越:

SyntaxError: /vagrant/playtoday/app/models/pricing_period.rb:12: syntax error, unexpected '}', expecting => 
...weekday} & {end_day >= weekday}} 
...        ^
/vagrant/playtoday/app/models/pricing_period.rb:13: syntax error, unexpected '}', expecting => 
...e <= time} & {end_time >= time}} 
...        ^

它甚至有可能使用範圍的條件?我還沒有弄清楚。

回答

0

看起來你有語法錯誤。你應該在where塊中使用括號而不是大括號。

scope :within_weekday, -> (weekday) { where { (start_day <= weekday) & (end_day >= weekday) } 
scope :within_time, -> (time) { where { (start_time <= time) & (end_time >= time) } 
1

沒有運營商=<(不僅是不確定的,而且是非法的)。您可能打算使用<=

如何記住:

  • 令牌=>保留給哈希文字和爲rescue收到錯誤。因此「等於或大於」不能由此表示。它表示爲>=
  • 您希望操作符表示法一致;因爲有>=,所以您希望<=(而不是=<)爲「等於或小於」。
+0

這是一個粗心的錯誤,但我仍然不幸工作。我更新了OP以顯示錯誤 – Batman

相關問題