Setting a has_many :through association on a :belongs_to association

November 12, 2010

  • Rails
  • Ruby
  • ruby-on-rails
  • associations
  • has-many
  • delegate
  • method
  • create-a-delegate
  • belongs-to
  • has-many-through

I was trying to figure out how would I set a has_many..through relationship on belongs_to association, similar to the one which we can implement on the has_many association in rails. I mean

class Model2 < ActiveRecord::Base
     has_many :model1s
     has_many :model3s, :through => :model1s
end

This is possible as we all know. But I wanted to implement something like:

class Model2 < ActiveRecord::Base
     belongs_to :model1
     has_many :model3s, :through => :model1
end

Obviously this is not possible to implement this way, instead there are a couple of ways around this

  1. Create a method
  2. Create a delegate

1 : Create a method

class Model2 < ActiveRecord::Base
     belongs_to :model1

     def model3s
          model1.model3s
     end
end

It will definitely get you model C through the model B, but there is a problem in this, that it is actually not creating an association, instead it is just setting up an accessor. So the manipulations that can be carried out on an association will not be possible here. But it is just a way.

2 : Create a delegate

class Model2 < ActiveRecord::Base
     belongs_to :model1
     delegate :model3s, :to => :model1
end

Even this works but possesses the same problem as in the previous situation.

As rails doesn’t implicitly supports this I tried to do it explicitly, and obviously rails doesn’t like it as it is not creating an association :D. kidding. Well but please do tell me if you can find some other way to do it.

Have a great day. Hope this was helpful.


LOCATION

Mumbai, Maharashtra, India

AROUND THE WEB

Copyright © 2021