ActionController :: ParameterMissing param丢失或值为空:

时间:2016-01-19 03:23:07

标签: ruby-on-rails ruby-on-rails-4

当我尝试创建新的商家信息时,我收到以下错误,我无法弄清楚问题出在哪里。

ActionController::ParameterMissing in BusinessListingsController#create
param is missing or the value is empty: businesslisting

以下是business_listing_controller的代码:

class BusinessListingsController < ApplicationController
  def index
    @businesslistings = BusinessListing.all
  end

 def new
   @businesslisting = BusinessListing.new
 end

def create
  @businesslisting = BusinessListing.new(businesslisting_params)
  if @businesslisting.save
  redirect_to @businesslisting
 else
  render 'new'
 end
end

def show
  @businesslisting = BusinessListing.find(params[:id])
end

private 
  def businesslisting_params
    params.require(:businesslisting).permit(:title, :price, :city,    :industry)
  end
end 

查看/ business_listing /

<div class="row">
 <div class="col-md-6">
 <%= form_for(@businesslisting) do |f| %>

<%= f.label :title %>
<%= f.text_field :title %>

<%= f.label :price %>
<%= f.text_field :price %>

<%= f.label :city %>
<%= f.text_field :city %>

<%= f.label :industry %>
<%= f.text_field :industry %>

<%= f.submit "Create a Listing", class: "btn btn-primary" %>
<% end %>

谢谢!

2 个答案:

答案 0 :(得分:3)

问题是您没有遵循Rails命名约定。您的类为BusinessListing,但您将实例变量和参数引用命名为businesslistingBusinessListing(驼峰案例)基本上是两个单词,在使用实例变量名时应该匹配为蛇案例:business_listing

您的参数名称也是如此。 When you pass a model object into form_for,Rails使用类名来确定参数名称,因此我打赌实际的参数是business_listing,而不是businesslisting

只需在代码中将所有businesslisting更改为business_listing(以及businesslistingsbusiness_listings),您就不应再遇到此问题。

最重要的变化是:

params.require(:business_listing).permit(:title, :price, :city, :industry)

这本身就可以解决您当前的问题,但我强烈建议您在整个代码中遵循约定,以避免进一步的问题和混淆。

答案 1 :(得分:0)

Ubuntu 20.04 中使用 Rails 6 API时,我遇到了这个挑战。

我有一个Schools资源(控制器,模型和路线),我需要使用邮递员创建一所学校。 Schools资源有2个参数(名称和别名)。因此,我使用了 Params 指令来传递它,但出现错误:

app/controllers/schools_controller.rb:49:in `school_params'
app/controllers/schools_controller.rb:18:in `create'
Started POST "/schools" for ::1 at 2020-12-09 03:40:29 +0100
Processing by SchoolsController#create as */*
  Parameters: {"name"=>"The Prince School", "alias"=>"The Prince"}
Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms | Allocations: 122)
  
ActionController::ParameterMissing (param is missing or the value is empty: school):

Screenshot 1

这是我修复的方式

问题是,根据school中我的school_params,应用程序期望另一个名为SchoolsController的参数将封装其他参数:

def school_params
  params.require(:school).permit(:name, :alias)
end

首先,我在 Header 部分中将Content-Type定义为application/json,然后在Postman的 Body 部分中将参数传递为使用此原始 JSON对象:

{
    "school": {
        "name": "The Prince School",
        "alias": "The Prince"
    }
}

enter image description here

enter image description here

效果很好。

资源Testing Rails 5 API with Postman

仅此而已。

我希望这会有所帮助