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.
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.
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).
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.
The easiest way:
class MyModel < ActiveRecord::Base belongs_to :parent, :class_name => 'MyModel' has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id' end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With