[英]ReNesting Resource Routes in Rails
所以我只是將我的一個對象作為我的用戶對象的嵌套資源。 現在我的所有鏈接都不起作用,我的索引也不顯示。 我收到錯誤:
/views/photos/index.html.haml第8行引發:
沒有路由匹配{:action =>“show”,:controller =>“photos”,:id => nil,:user_id => nil}缺少必需的密鑰:[:id,:user_id]
這條線是找到問題的地方:
= link_to photo.title, user_photo_path(@user, @photos)
這是我的照片對象的控制器:
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
我的路線看起來像這樣:
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
這是我的用戶控制器:
class UsersController < ApplicationController
def show
@user = User.find_by(params[:id])
@photos= @user.photos.order(:cached_weighted_score => :desc)
end
end
最后生成錯誤代碼的視圖:
.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
任何幫助表示贊賞。 我的最后一個改變是將照片路線添加到用戶路線下方。
第二個arg需要是一個來自循環的照片實例而不是@photo,這可能是零:
= link_to photo.title, user_photo_path(@user, photo)
更新1:您還需要在PhotosController#show中加載@user:
@user = User.find_by(params[:user_id])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.