Last active
December 14, 2015 13:49
-
-
Save caseydm/5096447 to your computer and use it in GitHub Desktop.
Rails Single Table Inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# model finance.rb | |
class Finance < ActiveRecord::Base | |
attr_accessible :amount, :date, :description, :type | |
belongs_to :users, :dependent => :destroy | |
end | |
# model income.rb | |
class Income < Finance; end | |
# model expense.rb | |
class Expense < Finance; end | |
# controller finances_controller.rb | |
class FinancesController < ApplicationController | |
before_filter :authenticate_user! | |
def index | |
@finances = current_user.finances.all | |
end | |
def new | |
@finance = Finance.new | |
end | |
def create | |
@finance = Finance.new(params[:finance]) | |
@finance.user_id = current_user | |
@finance.type = params[:finance_type] | |
if @finance.save | |
redirect_to finances_path notice: 'Item created.' | |
else | |
render action: "new" | |
end | |
end | |
end | |
# view entry form _form.html.erb | |
<%= form_for @finance do |f| %> | |
<% if @finance.errors.any? %> | |
<div id="error_explanation"> | |
<h2><%= pluralize(@finance.errors.count, "error") %> prohibited this from being saved:</h2> | |
<ul> | |
<% @finance.errors.full_messages.each do |msg| %> | |
<li><%= msg %></li> | |
<% end %> | |
</ul> | |
</div> | |
<% end %> | |
<%= select_tag(:finance_type, options_for_select([['Income', 'Income'], ['Expense', 'Expense']])) %> | |
<div class="field"> | |
<%= f.label :description %><br /> | |
<%= f.text_field :description %> | |
</div> | |
<div class="field"> | |
<%= f.label :amount %><br /> | |
<%= f.text_field :amount %> | |
</div> | |
<div class="field"> | |
<%= f.label :date %><br /> | |
<%= date_select :finance, :date %> | |
</div> | |
<div class="actions"> | |
<%= f.submit %> | |
</div> | |
<% end %> | |
# routes.rb | |
PhotogDesign::Application.routes.draw do | |
devise_for :users, path_names: {sign_in: "login", sign_out: "logout"} | |
resources :clients | |
resources :finances | |
resources :income, :controller => 'finances' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment