Ruby-on-rails Rails 4 错误“参数丢失或值为空:”在创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28664074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:05:18  来源:igfitidea点击:

Rails 4 error "param is missing or the value is empty:" in create

ruby-on-railsrubyruby-on-rails-4strong-parameters

提问by jeffhale

I've looked at several tutorials, the ruby guides, and several stackoverflow questions. I tried first with simple_form and now the old fashioned way and can't figure out why the params aren't being passed.

我看过几个教程、ruby 指南和几个 stackoverflow 问题。我首先尝试使用 simple_form,现在尝试使用老式方法,但无法弄清楚为什么没有传递参数。

Controller:

控制器:

def new
  @topgem = Topgem.new
end

def create 
  @topgem = Topgem.new(topgem_params)

  if @topgem.save
    redirect_to @topgem
  else
    render 'new'
  end

...

...

 private
    def topgem_params
      params.require(:name).permit(:url, :description, :downloads, :last_updated)
    end

Model:

模型:

class Topgem < ActiveRecord::Base

  has_many :votes
  has_many :users, through: :votes

  validates :name, presence: true, uniqueness: true, :length => {
    :minimum =>2,
    :maximum =>50}

  validates :url, presence: true
  validates :description, presence: true 
  validates :downloads, numericality: { only_integer: true }
end

new.html.erb

新的.html.erb

<%= form_for(@topgem) do |f| %>


  <%= f.label :name %>:
  <%= f.text_field :name %><br />

  <%= f.label :url %>:
  <%= f.text_field :url %><br />

   <%= f.label :description %>:
  <%= f.text_field :description %><br />

   <%= f.label :downloads %>:
  <%= f.number_field :downloads %><br />


  <%= f.submit %>
<% end %>

The error I am getting:

我得到的错误:

ActionController::ParameterMissing at /topgems
param is missing or the value is empty: name

here are select instance variables:

这里是选择实例变量:

Instance Variables

实例变量

@_action_has_layout 
true

@_routes    
nil

@_headers   
{"Content-Type"=>"text/html"}

@_status    
200

@_params    
{"utf8"=>"?", "authenticity_token"=>"Gx/UwvcvWZYWAUHxWGYlUQB/PNNUniBpCjlM1WEHAm+luYl94Kky5Ae9Ur40YVtrN2ebEEX8C0G3Cewu/SJSow==", "topgem"=>{"name"=>"bfgf", "url"=>"dd", "description"=>"ff", "downloads"=>"343"}, "commit"=>"Create Topgem", "controller"=>"topgems", "action"=>"create"}

回答by messanjah

You have required params[:name], but the actual params are params[:topgem][:name].

您需要params[:name],但实际的参数是params[:topgem][:name]

Change your topgem_paramsmethod to

将您的topgem_params方法更改为

params.require(:topgem).
  permit(
    :name,
    :url,
    :description,
    :downloads,
    :last_updated
  )