Menu

Post image 1
Post image 2
1 / 2
0

Self Referential Associations in Rails - simpler than it sounds

DEV Community·Shamila TP·30 days ago
#eLIjhuFi
#rails#ruby#ror#programming#manager#employee
Reading 0:00
15s threshold

Tbh I had no idea this was even a thing until recently. I've been working with Rails for a while now and somehow never came across it. So let me explain it the way I understood it. You know how we normally do associations in Rails, User has many Posts, Post belongs to User. Two different models, two different tables. Simple. But what if a model needs to reference itself? Like same table, same model, but pointing to another record in the same table? That's all a self referential association is. The example that made it click for me was Employee and Manager. A manager is just another employee right? So both live in the same employees table. Let's build it: rails new self_referential --api cd self_referential rails g model Employee name:string manager_id:integer rails db:migrate Enter fullscreen mode Exit fullscreen mode The key column here is manager_id — it just points back to the same table. Now if you go to Rails console and try alice.manager , you'll get a NoMethodError .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More