Rails get nested attribute based in has_many relation

I have 3 classes

Class User < ActiveRecord::Base

 has_many :dogs

end

Class Dog < ActiveRecord::Base

 belongs_to :user
 has_many :tags

end

class Tag < ActiveRecord::Base
  belongs_to :dog
end

I've tried execute User.dogs and I get a list of Dog entities like this:

[Dog, Dog, Dog, Dog]

If I access to a Dog entity in the array, I get all the attributes of Dog and works fine. But my problem it's that I need include Tag entity inside Dog.

By example if i do this

user.dogs.each do |dog_entity|
   puts dog_entity.tags #Prints the tags related value of Tag in Dog.
 end

How achieves that when i execute User.dogs the Tag related value to Dog come inside in each Dog in the array?

Upvotes: 0

Views: 568

Answers (1)

Aleksey
Aleksey

Reputation: 2309

dogs is association so you should call it on object not on model.

I think this should work

user.dogs.includes(:tags).each do |dog|
  puts dog.tags
end

Notice that user is object not model.
includes(:tags) allows us to avoid n+1 problem.

Please also notice that model should have singular name, i.e. Dog not Dogs.

Upvotes: 1

Related Questions