views:

1085

answers:

1

Rails has a has_one :through association that helps set up a one-to-one association with a third model by going through a second model. What is the real use of that besides making a shortcut association, that would otherwise be an extra step away.

Taking this example from the Rails guide:

class Supplier < ActiveRecord::Base
  has_one :account
  has_one :account_history, :through => :account
end

class Account < ActiveRecord::Base
  belongs_to :supplier
  has_one :account_history
end

class AccountHistory < ActiveRecord::Base
  belongs_to :account
end

might allow us to do something like:

supplier.account_history

which would otherwise be reached as:

supplier.account.history

If it's only for simpler access then technically there could be a one-to-one association that connects a model with some nth model going through n-1 models for easier access. Is there anything else to it that I am missing besides the shortcut?

+3  A: 

Hi, my guess would be:

  1. Logic, ok it might sounds a bit weak for this but it would be logical to say that "i have a supplier who has an account with me, i want to see all the account history of this supplier", so it makes sense for me to be able to access account history from supplier straight

  2. Efficiency, this for me is the main reason i would use :through, simply because this issues a join statement rather than calling supplier, and then account, and then account_history. noticed the number of database calls?

    • using :through, 1 call to get the supplier, 1 call to get account_history (rails automatically used :join to retrieve through account)

    • using normal association, 1 call to get supplier, 1 call to get account, and 1 call to get account_history

that's what i think =) hope it helps!

Staelen
I think the logic argument is pretty valid. Sounds more natural to say, get me this supplier's account history and not supplier's account's history. Very subtle but still easier to remember considering Ruby/Rails philosophy of flowing sentences rather than code. I know we can see the actual DB queries being issued but does Rails specify how these method calls would translate to SQL?
Anurag