Joe
Joe

Reputation: 2440

Chaining belongs_to relationships in Rails

So I'm working with a set of models that have straightforward belongs_to relationships. For example D belongs_to C which belongs_to B which belongs_to A. I often find myself needing to get access to "D's A", which I would typically write d_instance.c.b.a, but that gets old really quick.

Is there some magic I can add to the model of D which would jump me directly to d_instance.a?

Upvotes: 1

Views: 368

Answers (2)

RustyToms
RustyToms

Reputation: 7810

You can't use through with belongs_to, but you can use delegate. Here is the documentation for delegate: http://api.rubyonrails.org/classes/Module.html#method-i-delegate

You can use delegate on a model to call a method from another class as if it belonged to the model. In these example, uppercase is the class and lowercase is either an instance of the class or a method name. So in your case D has a method #c such that d.c returns the associated instance of C. C has a method #b such that c.b returns the associated instance of B, and B has a method #a that returns the associated instance of A.

If you go to the D model and delegate #b to C, when you call d.b it will be the same as if you called d.c.b. As this is probably confusing, here is the code you need:

class D < ActiveRecord::Base
  attr_accessible :this, :that, :the_other

  belongs_to :c

  delegate :b, to: :c
  delegate :a, to: :b

end

Once you have restarted your server d.a will give you the same result as d.c.b.a

Upvotes: 1

Zajn
Zajn

Reputation: 4088

One way to do this would be to create a method for instances D that returns the proper association:

class D
...
  def a
    self.c.b.a
  end
end

Upvotes: 1

Related Questions