Search code examples
ruby-on-railshas-manysingle-table-inheritance

Single table inheritance and has_many in rails


I'm making a simple financial app for funzies. I modeled credits and debits using single table inheritance, where both inherit from transactions. However, each transaction belongs to a user:

class Transaction < ActiveRecord::Base
  belongs_to :user
end

class Debit < Transaction
end

class Credit < Transaction
end

I could create separate controllers for credits and debits and do something like this:

@debit = current_user.debits.build(params[:debit])
...
@credit = current_user.credits.build(params[:credit])
...

But user does not have the methods debits or credits, only transactions. Alternatively, I could define a single transactions controller:

@transaction = current_user.transactions.build(params[:transactions])

But then the type is null, and how should I set that if it's protected from mass assignment? It's a bit of pickle either way. Except that pickles taste good.


Solution

  • You can explicitly set the type of the transaction in your second example by doing:

    @transaction = current_user.transactions.build(params[:transactions])
    @transaction.type = "Debit"
    @transaction.save
    

    The only problem with this is that the @transaction instance variable will not be of type Debit until it's saved and reloaded into a different variable.