Guillaume
Guillaume

Reputation: 335

Use many has_one relation on the same model

I have a model match like this:

class Match < ActiveRecord::Base
  belongs_to :match, foreign_key: 'parent'
  belongs_to :match, foreign_key: 'child_left'
  belongs_to :match, foreign_key: 'child_right'
end

Many match represent a tree.

I would like set the foreign key to use Match.first.child_left return me the object match and not just an integer who represents is id.

Better, can I use in this case the has_one relation? because it use each the model match but with a different foreign_key.

Even better, can I be sure than when I put a child_left in a match it will set the parent attribute on the child match with the db or should I do it with ruby?

Upvotes: 0

Views: 50

Answers (1)

makhan
makhan

Reputation: 4009

Try:

class Match < ActiveRecord::Base
  belongs_to :parent, class_name: 'Match'
  belongs_to :child_left, class_name: 'Match'
  belongs_to :child_right, class_name: 'Match'
end

Your matches table should have integer fields parent_id, child_left_id, child_right_id. You should be able to use it like this:

Match.first.child_left

Upvotes: 2

Related Questions