Search code examples
ruby-on-railsnested-resources

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!


Solution

  • 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.