You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7报错:article参数缺失或值为空,求解决方案

问题:Rails中ArticlesController的article_params报错“param is missing or the value is empty: article”

问题描述

在Rails项目中使用ArticlesController时,触发article_params方法时报错:param is missing or the value is empty: article,尝试多种方案未解决,附上控制器及视图相关代码请求排查。

控制器代码

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def create
    # render plain: params[:article].inspect
    @article = Article.new(article_params)
    if @article.save
        redirect_to @article
    else
        render action: 'new'
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
        redirect_to @article
    else
        render action: 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy(article_params)
  end

  private

  def article_params
      params.require(:article).permit(:title, :text)
  end
end

视图代码(index.html.erb)

<h3>The articles list</h3>

<% @articles.each do |article|%>
    <h4><%= article.title%></h4>
    <p><%= article.text%></p>
    <p><%= link_to 'Show', article_path(article)%></p>
    <p><%= link_to 'Edit', edit_article_path(article)%></p>
    <p><%= button_to 'Delete', article_path(article), data: {turbo: false}, method: :delete%></p>
    <hr/>
    <%= params.inspect%>
<% end %>

排查与解决

报错的核心原因是destroy方法中的错误调用:
@article.destroy(article_params) 这一行完全没必要,destroy方法不需要传入任何参数,而且DELETE请求的参数里只有:id,根本不存在:article键,调用article_params会触发params.require(:article)的校验失败,直接抛出你遇到的错误。

修改后的destroy方法:

def destroy
  @article = Article.find(params[:id])
  @article.destroy
  redirect_to articles_path # 可选:删除后跳转回文章列表页
end

另外补充两个需要确认的点:

  • 确保new.html.erb和edit.html.erb中的表单是基于@article构建的(比如用form_with(model: @article)),这样表单提交时参数会被包裹在:article键下,保证create和update方法中的article_params能正常工作。
  • 检查路由配置,确保resources :articles已正确添加,保证各请求路径和方法映射正确。

内容的提问来源于stack exchange,提问作者Vladimir Lozitskiy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:47:16