简体   繁体   中英

Querying on nested attribute

I have a set of stores, that again have locations . These locations have different business_hours . The way I store the business hours are:

 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

so I have a time on open_at and at close_at . What I'd like to get from the store, is the locations that are available at the time that I query.

So for example today is Wednesday, and my local time is 12:40. I want it to return all the locations that are open on Wednesday at 12:40.

I've started writing a method but unsure how to complete it.

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
store.locations.join(:business_hours).where("week_day = ? AND open_at < ? < close_at", current_day, Time.zone.now)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM