7

Say I have a model of type A, and a model of type B, which has the fields a_id a2_id. I want to have something like:

class B
  belongs_to :a
  belongs_to :a (using a2)
end

Does anyone know how I would do this? I am trying to use the class B to link similar objects in my DB.

Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
joncalhoun
  • 1,498
  • 1
  • 17
  • 22

2 Answers2

6

You can do this

class B
  belongs_to :a
  belongs_to :a2, foreign_key: 'a2_id', class_name: 'A'
end
Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
2

or even this:

class B < ActiveRecord::Base
  attr_accessible :a2_id, :a_id, :name
  belongs_to :a
  belongs_to :a2, class_name: "A"
end
bento
  • 2,079
  • 1
  • 16
  • 13