轨道控制器专用方法错误"cannot find album without ID"



我正试图在相册#索引页中显示所有相册,但我的相册控制器中出现错误"找不到没有ID的相册"。我知道问题是没有params,但我已经在我的应用程序中多次使用带有params[:id]的find方法,到目前为止还没有遇到这个问题。

作为参考,相册有很多评论,通过评论有很多用户。用户有许多评论,并通过评论拥有许多相册。

我还没有建立我的评论控制器,所以这是无关的。

错误如下:

ActiveRecord::RecordNotFound in AlbumsController#index
Couldn't find Album without an ID
Extracted source (around line #40):
38
39
40
41
42
43

def set_album
@album = Album.find(params[:id])
end
def album_params
Rails.root: /Users/melc/review_project
Application Trace | Framework Trace | Full Trace
app/controllers/albums_controller.rb:40:in `set_album'
Request
Parameters:
None

这是我的相册控制器:

class AlbumsController < ApplicationController
before_action :set_album, only: [:index, :show, :edit, :update]
def index
@albums = Album.all
@current_user
end
def show
end
def new
@album = Album.new
end
def create
@album = Album.new(album_params)
if @album.save
redirect_to album_path(@album)
else
render :new
end
end
def edit
end
def update
if @album.update(album_params)
redirect_to album_path(@album), notice: "Your album has been updated."
else
render 'edit'
end
end
private
def set_album
@album = Album.find(params[:id])
end
def album_params
params.require(:album).permit(:artist, :title, :avatar)
end
end

这是我的相册#索引视图:

<h2>All Albums</h2>
<br>
<br>
<% if @album.avatar.attached? %>
<image src="<%=(url_for(@album.avatar))%>%" style="width:350px;height:350px;">
<% end %>
<br>
<%= @album.artist %> -
<%= @album.title %>
<br>
<%= link_to "Edit Album", edit_album_path %><br><br>
<%= link_to "Upload a New Album", new_album_path %>

这是routes.rb文件:

Rails.application.routes.draw do
get '/signup' => 'users#new', as: 'signup'
post '/signup' => 'users#create'
get '/signin' => 'sessions#new'
post '/signin' => 'sessions#create'
get '/signout' => 'sessions#destroy'
resources :albums do
resources :reviews
end
resources :users
root to: "albums#index"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

您需要在这里更改几件事:

  1. 在AlbumsController上,您需要从"预加载"相册的操作中删除index

    before_action :set_album, only: [:show, :edit, :update]

  2. 您需要将相簿对象传递到视图中的路线:

    <%= link_to "Edit Album", edit_album_path(@album) %><br><br>

希望这能帮助

编辑:关于头像问题,看起来你在索引中显示相册,但你没有迭代它们,比如:

<h2>All Albums</h2>
<% @albums.each do |album| %>
<br>
<br>
<% if album.avatar&.attached? %>
<image src="<%=(url_for(album.avatar))%>%" style="width:350px;   height:350px;">
<% end %>
<br>
<%= album.artist %> - <%= album.title %>
<%= link_to "Edit Album", edit_album_path(album) %><br><br>
<br>
<% end %>
<%= link_to "Upload a New Album", new_album_path %>`

相关内容

最新更新