There are cases where you might not want to add a specific field to a table. In your example you really only need one table as you can just add account_number
and credit_ranking
to the suppliers
table. But sometimes it's a good idea to store the data across several tables. Then you have to use the has_one
(one-to-one) relationship.
In your example you could also just add the attribute supplier_id
to account_histories
and replace has_one :account_history, :through account
with just has_one :account_history
but that would be redundant and also complicate your code as you would need to make sure that you don't change one attribute and forget to update the other one.
UPDATE:
If you don't add the supplier_id
attribute to account_histories
then Rails won't be able to determine which row from that table belongs to which supplier. The only way to find that out is to look in the related accounts
table. Without accounts
you can't determine which account_history
belongs to a supplier as the accounts_histories
table doesn't have any foreign keys for the suppliers
table.
To get the account_history
for a supplier without the :through
option you would have to do this:
Supplier.find(id).account.account_history
:through
allows you to replace it with this:
Supplier.find(id).account_history
As you've written in your update you could add the credit_ranking
attribute to accounts
and have only two tables. That would be even more simple but you just might want not to store that attribute in the same table (because maybe you already have lots of other attributes and don't want to add even more of them).