I have created few models which are shown below.
Base models are TransactionType and TransactionItem
ExpenseType and IncomeType derives from TransactionType.
Expense and Income derives from TransactionItem.
2.1.2 :006 > Expense.new(:note => "a soda", :expense_type =>
ExpenseType.first)
ExpenseType Load (0.1ms) SELECT "transaction_types".* FROM
"transaction_types" WHERE "transaction_types"."tran_type" IN
('ExpenseType') ORDER BY "transaction_types"."id" ASC LIMIT 1
ActiveModel::MissingAttributeError: can't write unknown attribute
`expense_type_id'
from
It would be great if someone shares your idea for solving this.
I don’t think this is an inheritance problem. What does the schema for your transaction_items table look like? The error message suggests that it doesn’t have a column expense_type_id, which is what belongs_to :expense_type is going to be looking for.
A wild guess: maybe you’ve got a transaction_type_id column instead? In that case, you should use this on Expense:
the code you posted has a single transaction_items table, but two classes (Income and Expense) that both descend from ActiveRecord::Base. That definitely won’t work. If you really want a common transaction_items table, you’ll need to include a column to put the STI type in and a base class of TransactionItem rather than a module.
as noted previously, if you have a column on transaction_items called transaction_type_id but want to refer to the corresponding association as expense_type or income_type, you’ll need to pass the foreign_key option to belongs_to.