Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Serialization TimeOfDay with Rails and jsonb
#!/usr/bin/env ruby
# Supplies TimeOfDay class that includes parsing, strftime, comparison, and arithmetic
gem 'tod', '~> 2.2'
ActiveRecord::Schema.define do
add_column :businesses, :force => true do |t|
t.jsonb :business_hours
### It turns out you need to set the business_hours to nil, and then Rails will take care of setting the attributes.
### I was previously setting the migration to include default: '{}', null: false and receiving a
### IndexError (string not matched) error
class Business < ActiveRecord::Base
store_accessor :business_hours, :sunday_opens_at, :sunday_closes_at,
# ...
serialize :sunday_opens_at, Tod::TimeOfDay
serialize :sunday_closes_at, Tod::TimeOfDay
# ...
### Using a store accessor allows you to specify the keys you want to access directly without referencing the JSONB field
### Note: I had an issue declaring serialize before the store accessor
module ApplicationHelper
def time_select_options(step=15)
tod = 0
times = []
96.times do
times << [tod.strftime("%l:%M %P"), tod]
tod = tod + step.minutes
<%= form_with(model: storage_property) do |form| %>
<% I18n.t('date.day_names').each_with_index do |day, wday| %>
<td class="day">
<div class="form-group">
<%= form.label :"#{day.downcase}_opens_at" %>
<%= :"#{day.downcase}_opens_at", time_select_options, label: "Open Time", include_blank: "Closed" %>
<div class="form-group">
<%= :"#{day.downcase}_closes_at", time_select_options, label: "Close Time", include_blank: "Closed" %>
<% end %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment