Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I do self-reference with ruby on rails?

I want to self-referentiate a model in a RoR app but, I don't know exactly how. I want to save a linked list where the next node has the id of the previous one. how can I do this rails way? It is a one-to-one relation.

like image 443
JRafaelM Avatar asked May 23 '11 12:05

JRafaelM


People also ask

How use self join in rails?

A self-join is a join in which a table is joined with itself using a FOREIGN KEY which references its own PRIMARY KEY. This can be viewed as a join of two copies of the same table. Let's take a closer look at this from the SQL perspective.

What is self association in rails?

Self-referential association means we create a JOIN MODEL, such as Friendship, for example, which links another model, such as User to itself, so a user can have many friends (which are other users), and a friend can be befriended by a user ( a follower and a followed).

Can you think of another example of a table that can have a self-referential relationship?

Twitter followers, Facebook friends, Linkedin connections, and Medium fans are all examples of self-referential relationships. Each of these relationships can be set up just two tables: the user table, and a join table to link it to itself.


1 Answers

The easiest way:

class MyModel < ActiveRecord::Base   belongs_to :parent, :class_name => 'MyModel'   has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id' end 
like image 107
Hck Avatar answered Oct 13 '22 17:10

Hck