【发布时间】:2020-04-12 07:27:28
【问题描述】:
我正在尝试在专辑#index 页面中显示所有专辑,但我的专辑控制器中出现错误“找不到没有 ID 的专辑”。我知道问题是没有参数,但我已经在我的应用程序中多次使用带有 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
这是我的专辑#index 视图:
<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
【问题讨论】:
-
为索引页面创建
set_album通常是没有意义的,我认为您正在尝试显示专辑列表。我说“假定”是因为那将是典型的索引页面,但您显示的索引页面视图不显示列表。事实上,params[:id]没有值发送到控制器(错误消息中的Request parameters: none)。 -
所以从
before_action中删除:index。然后修复您的索引视图以显示由控制器#index 方法创建的专辑列表@albums。
标签: ruby-on-rails activerecord