Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self referential "twin" has_one association

I'm in Rails 3.2.2 and I have a Variant class:

class Variant < ActiveRecord::Base

   has_one :twin_variant

end

I'd like to be able to associate two objects from this class to became "twins". I'd like to create:

v1 = Variant.new
v1.name = "Fantastic variant"
v1.save

Then I'd like to have a method to create a twin variant:

v2 = Variant.new
v2.name = "Fantastic variant twin"
v2.save

v1.twin_variant = v2

Then the 2 objects should become associated with each other, so that:

v1.twin_variant
=> v2

v2.twin_variant
=> v1

Is this possible? How should I build the association?

like image 741
Augusto Avatar asked Dec 14 '12 10:12

Augusto


1 Answers

Given the following model

class Variant < ActiveRecord::Base
  attr_accessible :name, :variant_id

  has_one :twin_variant, class_name: "Variant", foreign_key: :variant_id
  belongs_to :twin, class_name: "Variant", foreign_key: :variant_id
end

You can setup the cyclic relationship with

v1 = Variant.create(name: "Variant #1")
v2 = Variant.create(name: "Variant #2")

v1.twin_variant = v2
v2.twin_variant = v1

and you can check this with

Variant.where(name: "Variant #2").first.twin_variant.name # "Variant #1"
Variant.where(name: "Variant #1").first.twin_variant.name # "Variant #2"
like image 131
deefour Avatar answered Sep 20 '22 22:09

deefour