Josh Johnson
Josh Johnson

Reputation: 563

Rails has_many dual relationship with other model

I'm trying to get two has_many relationships from one model to another. Specifically, I want:

class Driver < Active:Record::Base
  has_many :reservations
  has_many :requested_reservations

and

class Reservations < Active:Record::Base
  belongs_to :driver
  belongs_to :requester

The first one is a normal has_many/belongs_to relationship using driver_id on the reservations model.

But for the second one, I want to be able to call @driver.requested_reservations and @reservation.requester, and have it use the requester_id column in the Reservations class. What do I need to put at the end of those has_many and belongs_to lines to get it to work properly?

Upvotes: 0

Views: 315

Answers (2)

ardavis
ardavis

Reputation: 9895

I believe you can set the class and foreign key to get the desired results.

class Driver < Active:Record::Base
  has_many :reservations
  has_many :requested_reservations, class_name: 'Reservation', foreign_key: 'your_id'
  ...
end

class Reservations < Active:Record::Base
  belongs_to :driver
  belongs_to :requester, class_name: 'Driver', foreign_key: 'requester_id'
  ...
end

Upvotes: 2

Aayush Kumar
Aayush Kumar

Reputation: 1618

There are similar questions that have been asked before. See the following links for more information:

Rails multiple associations between two models

how to specify multiple relationships between models in rails using ActiveRecord associations

Upvotes: 0

Related Questions