Skip to content

Instantly share code, notes, and snippets.

@drakmail
Created February 20, 2016 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drakmail/ab5373a6da57e96b17eb to your computer and use it in GitHub Desktop.
Save drakmail/ab5373a6da57e96b17eb to your computer and use it in GitHub Desktop.
STI example
class DrinkHabit < Habit
# DB structure
# id:integer
# title:text
# food_amount:integer
# drink_time:datetime
# type: string
end
class FoodHabit < Habit
# DB structure
# id:integer
# title:text
# food_amount:integer
# drink_time:datetime
# type: string
end
class Habit < ActiveRecord::Base
# DB structure
# id:integer
# title:text
# food_amount:integer
# drink_time:datetime
# type: string
belongs_to :user
end
class HabitsController < ApplicationController
def update
habit = Habit.find(params[:id])
if habit.update habits_params
redirect_to habit_path(habit)
else
render 'show'
end
end
protected
def habits_params
params.require(:habit).permit(:id, :title, :food_amount, :drink_time)
end
end
<%= form_for @habit do |f| %>
<%= f.text_field :title %>
<%= if @habit.is_a? FoodHabit %> <!-- better to use rendering of partials and helper -->
<%= f.text_field :food_amount %>
<% end %>
<% if @habit.is_a? DrinkHabit %>
<%= f.text_field :drink_time %>
<% end %>
<%= f.submit %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment