Gibson
Gibson

Reputation: 2085

How to retrieve user 2nd level resource with nested resources

I have a user model that has many photos and those photos have many tags.

My routes:

resources :users do
  resources :photos do  
    resources :tags
  end
end

My view:

<%= @user.photos.tags.count %>

I don't know how to retrieve all the tags a user has, since it's a 2nd level nested resource. Any idea? Thanks guys!

Upvotes: 1

Views: 32

Answers (2)

Sergey Alekseev
Sergey Alekseev

Reputation: 12300

Here you go:

class User < ActiveRecord::Base
  has_many :photos, dependent: :destroy
  has_many :tags, through: :photos
end

class Photo < ActiveRecord::Base
  belongs_to :user
  has_many :tags, dependent: :destroy
end

class Tag < ActiveRecord::Base
  belongs_to :photo
end

# @user.tags

Just scroll to the end of http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association.
By the way, don't be confused with nested resources and associations as terms.

Upvotes: 2

Ricardo Nacif
Ricardo Nacif

Reputation: 508

You can do:

class User < ActiveRecord::Base 
  has_many :photos
  has_many :tags, through: :photos
end

And at the view:

<%= @user.tags.count %>

Upvotes: 2

Related Questions