在 rails 中为脚手架创建的控制器创建新操作时出错

Error when creating new action to scaffold created controller in rails

我正在尝试使用脚手架在我之前创建的博客中创建一个新的操作列表。我在

中遇到错误

Couldn't find Blog with 'id'=

在 controllers/blogs_controller.rb

这是我的控制器代码。

class BlogsController < ApplicationController
before_action :authenticate_user!, :except => [:index, :show]
layout 'admin', only:[:new, :create, :update, :destroy, :edit, :list]
before_action :set_blog, only: [:show, :edit, :update, :destroy, 
:list]

# GET /blogs
# GET /blogs.json
def index
 @blogs = Blog.all
end

# GET /blogs/1
# GET /blogs/1.json
def show
end

def list
 @blogs = Blog.all
end

# GET /blogs/new
def new
 @blog = Blog.new
end

# GET /blogs/1/edit
def edit
end

# POST /blogs
# POST /blogs.json
def create
 @blog = Blog.new(blog_params)

 respond_to do |format|
  if @blog.save
    format.html { redirect_to @blog, notice: 'Blog was successfully          
  created.' }
    format.json { render :show, status: :created, location: @blog }
  else
    format.html { render :new }
    format.json { render json: @blog.errors, status: :unprocessable_entity }
  end
end
end

# PATCH/PUT /blogs/1
# PATCH/PUT /blogs/1.json
def update
 respond_to do |format|
  if @blog.update(blog_params)
    format.html { redirect_to @blog, notice: 'Blog was successfully updated.' }
    format.json { render :show, status: :ok, location: @blog }
  else
    format.html { render :edit }
    format.json { render json: @blog.errors, status: :unprocessable_entity }
  end
end
end

# DELETE /blogs/1
# DELETE /blogs/1.json
def destroy
@blog.destroy
respond_to do |format|
  format.html { redirect_to blogs_url, notice: 'Blog was successfully destroyed.' }
  format.json { head :no_content }
end
end

private
 # Use callbacks to share common setup or constraints between actions.
 def set_blog
  @blog = Blog.find(params[:id])
 end

 # Never trust parameters from the scary internet, only allow the white list through.
def blog_params
  params.require(:blog).permit(:title, :description)
end

结束

我的routes.rb是

Rails.application.routes.draw do

resources :blogs do
 collection do
    get :list, :as => 'list'
 end
end
 root to: 'home#index'
end

现在,在我名为 list.html.erb 的新控制器视图中,我需要查看除正常显示操作之外的所有博客 post。

在我的list.html.erb

<td><%= link_to blog.title %></td>

错误显示在 set_blog

private
 # Use callbacks to share common setup or constraints between actions.
 def set_blog
   @blog = Blog.find(params[:id])
 end

通过在您的 set_blog 操作之前包含 :list 方法,您可以强制它使用 id 作为参数来查找特定的博客,但您想要的实际上是您在list方法,正在拉取所有博客

所以这个

 def set_blog
  @blog = Blog.find(params[:id])
 end

正在覆盖这个

def list
  @blogs = Blog.all
end

要解决这个问题

before_action :set_blog, only: [:show, :edit, :update, :destroy, :list]

为此,请在操作前从设置的博客中删除 :list 方法

before_action :set_blog, only: [:show, :edit, :update, :destroy]

删除

:list

来自 before_action

:set_blog