Finding the best way to extract work time from a database

I use Ruby on Rails, and I store working hours as follows:

CREATE TABLE "business_hours" (
 "id" integer NOT NULL PRIMARY KEY,
 "business_id" integer NOT NULL FOREIGN KEY REFERENCES "businesses",
 "day" integer NOT NULL,
 "open_time" time,
 "close_time" time)

(which appeared from the stream: Saving working hours in the database )

Now I want to pull out the clock for each day of the week and display it, and I'm trying to find the best (or at least good) way.

Should I just have a helper method that goes through getting days (from 0..6) for a given business identifier and assigns it a variable for the associated day? I feel that there should be a better way - with an array or something like that, but it hurts me to think about it, because I also have a form of "choose where you can edit any of the watches for this business."

Thanks for any guidance!

+3
4

enum column plugin, .

class BusinessHours < ActiveRecord::Migration
  def self.up
    create_table :business_hours do |t|
      t.integer   :business_id, :null => false
      t.enum      :day, :limit =>[:sun, :mon, :tue, :wed, :thu, :fri, :sat], :nill => false
      t.time      :open_time, :null => false
      t.time      :close_time, :null => false
    end
  end

  def self.down
    drop_table :business_hours
  end
end

, BusinessHour, .

   b = BusinessHour.find_by_business_id(2).first 
   p b.day.to_s.camelize #prints Sun/Mon/Tue etc.

enum_select enum_radio / :

+2

, 6 ( ) . , , .

0

? , .

class BusinessHour < ActiveRecord::Base
  serialize :hours
  ...
end

BusinessHour.create :business => @business, :hours => 
  {:mon => [mon_start_time, mon_end_time], :wed => [wed_start_time, wed_end_time],
   ...}

, . , , , - .

0

business_hours.

<% @business.business_hours.each do |hrs| %>
  <%= hrs.day_name %>: Open-<%= hrs.open_time %> Close-<%= hrs.close_time %>
<%- end -%>

business_hour.rb , , . day_name, .

default_scope :order => 'day ASC'

def day_name
  case self.day
    when 0 then "Sun"
    when 1 then "Mon"
    ...
  end
end
-1

Source: https://habr.com/ru/post/1733292/


All Articles