Nihal Nizar
Nihal Nizar

Reputation: 25

Rails - Association between two models with foreign key having different names

I have two models , Agent , Visit .

Class Agent 
:name

Class Booking 
:booked_by

I want a has many relation where an agent can have multiple bookings. I want the key to be name/booked by .

Upvotes: 0

Views: 187

Answers (2)

Surya
Surya

Reputation: 16002

Use foreign_key option like so:

class Agent < AR::Base
  has_many :bookings, :foreign_key => :booked_by
end

class Booking < AR::Base
  belongs_to :agent, :foreign_key => :booked_by
end

Fromhas_many doc andbelongs_to doc.

Upvotes: 1

Sajin
Sajin

Reputation: 1638

I think this is what you are looking for:

Class Agent

has_many    :names, class_name: 'Booking'

Class Booking

belongs_to  :booked_by, class_name: 'Agent'

Upvotes: 0

Related Questions