Forum: Ruby on Rails two has_many association for a single model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
57d7ce9a858a59eba57d3b08150fa563?d=identicon&s=25 Sachin Kale (sachinkale)
on 2009-01-25 05:09
Hi

I have following models

1. employee

2. transaction

Requirement - A transaction has a dealer(employee) and a
driver(employee).

I experimented following
---------

I have put -

/models/employee.rb :

has_many :transactions, :as => :dealer
has_many :transactions, :as => :driver

/models/transaction.rb :

belongs_to :dealer, :class => :employee, :foreign_key => :employee_id
belongs_to :driver, :class => :employee, :foreign_key => :employee_id


Transaction table has columns - dealer_id, driver_id,
------------------
Now the problem is how can I get something like @transaction.dealer.name
or
employee.transactions

------------
I certainly know that my experiment has basic flaws of understanding
associations.

Please help me!
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-01-25 09:00
(Received via mailing list)
On 25 Jan 2009, at 04:09, Sachin Kale wrote:

> driver(employee).
>
> I experimented following
> ---------
>
> I have put -
>
> /models/employee.rb :
>
> has_many :transactions, :as => :dealer
> has_many :transactions, :as => :driver

you're misusing :as here - that's for something completely different
>
>
> /models/transaction.rb :
>
> belongs_to :dealer, :class => :employee, :foreign_key => :employee_id
> belongs_to :driver, :class => :employee, :foreign_key => :employee_id
>
>
> Transaction table has columns - dealer_id, driver_id,

If that's the case then the :foreign_key option should be  'dealer_id'
and 'driver_id' (and thus unnecessary as that's the default).
The :class option is also supposed to be :class_name
I've got an example of something similar here:
http://www.spacevatican.org/2008/5/6/creating-mult...
Lastly, be wary of associations called transaction before Rails 2.3 -
the transaction method created by the association will stomp on an
internal method

Fred
57d7ce9a858a59eba57d3b08150fa563?d=identicon&s=25 Sachin Kale (sachinkale)
on 2009-01-25 15:51
Thanks, that was a great help. Also tip of 'transaction' naming was very
useful one. Thanks again!
This topic is locked and can not be replied to.