Search code examples
ruby-on-railsrouteshamlmembernested-resources

ReNesting Resource Routes in Rails


So I just made one of my objects a nested resource of my user object. Now all of my links don't work and my index won't show. I am getting the error:

/views/photos/index.html.haml where line #8 raised:

No route matches {:action=>"show", :controller=>"photos", :id=>nil, :user_id=>nil} missing required keys: [:id, :user_id]

with this line being where its finding the issue:

  = link_to photo.title, user_photo_path(@user, @photos)

This is my controller for my photos object:

class PhotosController < ApplicationController
before_action :find_photo, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :authenticate_user!, except: [:index, :show]

def index
    @photos = Photo.all.order(:cached_weighted_score => :desc)
end

def show
@comments = Comment.where(photo_id: @photo)
@photo = Photo.find(params[:id])
end

My routes look like this:

Rails.application.routes.draw do
devise_for :users
root 'photos#index'
resources :users do
resources :photos do
    member do
      get "like",  to: "photos#upvote"
      get "unlike", to: "photos#downvote"
    end
    resources :comments
  end
 end
end

This is my user controller:

class UsersController < ApplicationController

def show
  @user = User.find_by(params[:id])
  @photos= @user.photos.order(:cached_weighted_score => :desc)
end
end

finally the view that is generating the error code:

    .container
  .row
    .col-lg-12
      %h1.page-header Most Popular Photos
    - @photos.each do |photo|
      .thumbnail.col-lg-3.col-md-4.col-xs-6.thumb
        %h2
          = link_to photo.title, user_photo_path(@user, @photo)
          = link_to (image_tag photo.image.url(:small)), photo
        %p
          = photo.get_likes.size
          Likes
  = link_to "Add New Photo", new_photo_path

Any help is appreciated. My last change was adding the photos route into below the users route.


Solution

  • 2nd arg needs to be a photo instance from the loop not @photo which is probably nil:

    = link_to photo.title, user_photo_path(@user, photo)

    UPDATE 1: You also need to load up @user in PhotosController#show:

    @user = User.find_by(params[:user_id])