2
votes

I have a model and table that I believe is perfectly suited to STI. My table is called Finances and has two types: Income and Expenses. Besides type there are three other columns: description, amount, and date.

I'm getting very nervous using STI in Rails, since it requires some hacking. I'm too new to Rails to hack up the code. Even though it works, I don't understand it. That seems dangerous.

My question is, how do I set up my model, controller, and view if I do NOT use STI? Any best practices to group items in my model? Or do I just do Finances.where("type = 'Income'") before setting up a view?

Edit: I made a gist to show the code I'm working with. When I run it I get the error:

undefined method `incomes_path' for #<#<Class:0x007fbc95f60b40>:0x007fbc93883220>
2

2 Answers

4
votes

First, using STI is standard for Rails, so there is no need to feel nervous. And no need for "hacking". It has been used very successfully by many developers. And as you have seen, you can find tutorials and general information on the net.

If on the other hand, you decide NOT to use STI, you have the choice of using
(a) completely separate models with their own tables, which will result in a lot of duplicated code, or
(b) create you custom "STI-like" behaviour by hand. The second option could at least be interesting to learn more about Rails.

For example, in your Finances model you would define a scope incomes, like

scope :incomes, where(:type => 'Income')

then you can do Finances.incomes.

Then, if you have methods that apply only to one of the types, you should check that all records effectively are of the needed type.

Personally, I would advice you to use STI. You get a lot of functionality for free and you are doing it the Rails way. Imagine, for example, other developers reading your code, they will ask themselves, why you didn't use STI, blame it on ignorance and - if need be - refactor it using STI.

0
votes

STI is best if you are using inheritance structure like this. You don't really need to use Finances.where("type = 'Income'"). You can simply use Income.all. see these posts if they help you. http://www.therailworld.com/posts/18-Single-Table-Inheritance-with-Rails http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/