Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-referencing models in Rails 3

I have an Entity model and I want to display connections between the Entities. ie, Entity 1 is connected to Entity 2.

My thinking, right now, is to create a join model between the two called Connection and have it work like a traditional rails join table. Except have the columns be entity_one_id and entity_two_id, then establish a many-to-many relationship between Entity and Connection.

This seems like a really not-elegant way to do this. I was wondering if anyone had any better ideas? Maybe something more rails-esque that I'm just not seeing?

like image 451
Slick23 Avatar asked Jan 18 '11 18:01

Slick23


2 Answers

That's the most-common way to do it. If an entity is only ever connected to one other model, you could use a linked-list, tree-like structure.

Check out Ryan Bates' Railscast on self-joining models. It deals with a social-network-like system, but it still has principles you'll need and provides a great starting point

like image 187
sethvargo Avatar answered Sep 19 '22 14:09

sethvargo


You could use this implementation:

class User < ActiveRecord::Base
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
  has_many :friendships, :dependent => :destroy
end


class Friendship < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend, :class_name => "User"
end
like image 40
apneadiving Avatar answered Sep 22 '22 14:09

apneadiving