Ross
Ross

Reputation: 1562

Accessing a model through multiple relation

Hi I had a query is it a good idea to access one model through multiple models. For ex

I have 5 models as

Class A
    belongs_to :b
end 

Class B
    belongs_to :c
  has_many :a
end 

Class C
    belongs_to :d
  has_many :b
end 

Class D
    belongs_to :e
  has_many :c
end 

Class E
  has_many :d
end 

Now If I have a object of class E and I want to get the ojects of class A related to E, is it a right way to do this ..... Or should I add a relation between class E and some other class(B/C)

Upvotes: 0

Views: 80

Answers (1)

andrewpthorp
andrewpthorp

Reputation: 5096

It's really up to you. If you find yourself chaining these together and accessing them through a chain often, ask yourself if the relationship is accurate.

For instance, if I said my house has many rooms and a room has many doors, I could do this:

house.rooms.first.doors.first

But if I do that often, I obviously care about that the doors belong to the house. In this case I would rather be able to say:

house.doors.first_on_floor(2)

You can do this with

has_many :doors, :through => :rooms

Hope this helps!

Upvotes: 1

Related Questions