查询嵌套属性

时间:2016-02-24 11:43:45

标签: ruby-on-rails

我有一组商店,又有locations。这些位置具有不同的business_hours。我存储营业时间的方式是:

 create_table "business_hours", force: :cascade do |t|
    t.time     "open_at"
    t.time     "close_at"
    t.integer  "week_day",    default: 0, null: false
    t.integer  "location_id"
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
    t.index ["location_id"], name: "index_business_hours_on_location_id", using: :btree
  end

所以我有时间open_atclose_at。我想从商店获得的是我查询时可用的位置。

所以例如今天是星期三,我的当地时间是12:40。我想让它返回周三12:40开放的所有地点。

我已经开始编写方法,但不确定如何完成它。

def locations_open(local_time: Time.zone.now.in_time_zone('Stockholm'))
 current_day = local_time.wday
 store.locations.join(:business_hours).where(business_hours: { week_day: current_day })
 # and current time is open_at <> close_at
end

1 个答案:

答案 0 :(得分:0)

store.locations.join(:business_hours).where("week_day = ? AND open_at < ? < close_at", current_day, Time.zone.now)