Last active
December 14, 2015 21:09
-
-
Save caseydm/5149089 to your computer and use it in GitHub Desktop.
Rails STI
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 | |
# Attributes | |
attr_accessible :amount, :date, :description, :type | |
# Associations | |
belongs_to :users, :dependent => :destroy | |
end | |
# model expense.rb | |
class Expense < Finance; end | |
# model income.rb | |
class Income < Finance; end | |
# controller finances_controller.rb | |
class FinancesController < ApplicationController | |
before_filter :authenticate_user! | |
def index | |
@finances = current_user.finances.all | |
@finance_sum = current_user.finances.sum('amount') | |
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 _form.html.erb | |
<%= form_for @finance do |f| %> | |
<%= select_tag(:finance_type, options_for_select([['Income'], ['Expense']])) %> | |
<div class="field"> | |
<%= f.label :description %><br /> | |
<%= f.text_field :description %> | |
</div> | |
<div class="field"> | |
<%= f.label :amount %><br /> | |
<%= f.number_field :amount %> | |
</div> | |
<div class="field"> | |
<%= f.label :date %><br /> | |
<%= date_select :finance, :date %> | |
</div> | |
<div class="actions"> | |
<%= f.submit "Save" %> | |
</div> | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment