简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM