Code & Clay – Notes to self. Mainly Ruby/Rails.

Giving an association a custom name

Sometimes, it may be desirable to reference an association with a name that differs from the one generated from the table name.

I have a model named Steps. Each step can have many steps. Each step belongs to one other parent step.

class Step < ApplicationRecord
  belongs_to :step
  has_many :steps
a = Step.create
b = Step.create
c = Step.create

a.steps >> b
a.steps >> c

I could get the parent step of b like so:

# => #<Step:0x00007fdf24b916e8

I don’t think that’s intuitive enough though. Since I’m asking for the parent step, it should be more like:

# => #<Step:0x00007fdf24b916e8

Setting up the custom name is simple. I can supply the name of my choosing. Then, all I need to do is specify the class name and foreign id in the options.

class Step < ApplicationRecord
  belongs_to :parent, class_name: 'Step', foreign_key: :step_id
  has_many :steps

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6