rails class sti reminders code example
Example 1: rails class sti reminders
class AddNotes < ActiveRecord::Migration[5.2]
def change
create_table :notes do |t|
t.string :type
t.string :title
t.boolean :is_completed
t.jsonb :data, default: {}
t.timestamps
end
add_index :notes, :data, using: :gin
end
end
Example 2: rails class sti reminders
require 'test_helper'
require 'time'
class ReminderTest < ActiveSupport::TestCase
setup do
@reminder = Reminder.first
end
test 'should access methods from base class' do
assert_equal false, @reminder.completed?
end
test 'should not have data from alerts' do
assert_not_respond_to @reminder, :alert_at
end
end
class AlertTest < ActiveSupport::TestCase
setup do
@alert = Alert.first
end
test 'should access data from json' do
assert_equal Time.parse("2018-08-06 17:08:24 +0200"), @alert.alert_at
end
end
class NotesTest < ActiveSupport::TestCase
setup do
@notes = Note.all
end
test 'should return our domain model instead of base class' do
@notes.each do |n|
assert n.class == Alert || n.class == Reminder
end
end
end
Example 3: rails class sti reminders
sample_alert:
type: "Alert"
title: "Buy milk"
is_completed: false
data: '{"alert_at": "2018-08-06 17:08:24 +0200"}'
sample_reminder:
type: "Reminder"
title: "Short AAPL before autumn keynote"
is_completed: false
Example 4: rails class sti reminders
class Note < ActiveRecord::Base
def completed?
is_completed
end
end
class Reminder < Note; end
class Alert < Note
typed_store :data, coder: JSON do |s|
s.datetime :alert_at
end
end