Jeremy Thomas
Jeremy Thomas

Reputation: 6674

Rails Association: 2 occurrences of same model

I have a Consultation model that has a post_consultant and a consultant. Both post_consultant and consultant are references to the Employee model. So you could say:

Model

Class Consultation < ActiveRecord::Base
    has_one :employee # for consultant
    has_one :employee # for post_consultant
end

Migration

create_table "consultations", force: :cascade do |t|
  t.boolean "showed_up"
  t.boolean "signed_up"
  t.integer "client_id"
  t.integer "consultant_id"
  t.integer "post_consultant_id"
end

How am I supposed to write that?


Correct Model:

class Consultation < ActiveRecord::Base
    belongs_to :consultant, class_name: "Employee", foreign_key: "consultant_id"
    belongs_to :post_consultant, class_name: "Employee", foreign_key: "post_consultant_id"
end

Upvotes: 0

Views: 55

Answers (2)

krishna raikar
krishna raikar

Reputation: 2675

You can define multiple relation referring to same model.

Class Consultation < ActiveRecord::Base
    has_one :consultant, class_name: 'Employee', foreign_key: :consultant_id
    has_one :post_consultant, class_name: 'Employee', foreign_key: :post_consultant_id
end

Note: mention whichever foreign key you are using for each association using syntax above.

Upvotes: 0

raj_acharya
raj_acharya

Reputation: 665

Class Consultation < ActiveRecord::Base
    belongs_to :consultant, :class_name => "Employee", :foreign_key=> "consultant_id", dependent: :destroy
    belongs_to :post_consultant, :class_name=>"Employee", :foreign_key=> "post_consultant_id", dependent: :destroy
end

Upvotes: 3

Related Questions