Rails 4:如何处理未选择任何内容的已提交表单?

对不起,如果标题有点令人困惑。 我有一个带有字段nameItem的表单。 有一个文本字段,用户可以在其中输入名称并提交。 但是如果用户没有输入任何内容并点击提交,Rails会给我一个param not found: itemparam not found: item错误,我不知道该解决这个问题。

items_controller.rb

 def new @item = Item.new() respond_to do |format| format.html format.json { render json: @item } end end def create @item = Item.new(item_params) respond_to do |format| if @item.save format.html { redirect_to items_path } format.json { render json: @item, status: :created, location: @item } else format.html { render action: 'new', :notice => "Input a name." } format.json { render json: @item.errors, status: :unprocessable_entity } end end end private def item_params params.require(:item).permit(:name) end 

应用程序/视图/项目/ new.html.haml

 = form_for @item do |f| = f.label :name = f.text_field :name = f.submit "Submit" 

params.require(:item)部分是导致错误的原因。 当params [:item]不存在时处理错误的约定是什么?

答案已经很晚了,但我还是会为其他人写的。 如rails指南中所述,您需要在强参数中使用fetch而不是require,通过使用fetch,如果没有任何内容作为输入传递,则可以提供默认值。 就像是:

 params.fetch(:resource, {}) 

更新:

Scaffolded rails4 app: https : //github.com/szines/item_17751377

如果用户在创建新项目时将名称字段保留为空,则此方法有效…

看起来,它没有问题……

Development.log显示如果用户将字段保持为空,则参数将如下所示:

 "item"=>{"name"=>""} 

哈希中总有一些东西……

正如Mike Li在评论中提到的那样,出了点问题……因为不应该是空的这个参数[:item] ……

您可以使用.nil?检查是否为零.nil? ,在这种情况下params[:item].nil? 如果它是nil那将是true 。 或者你可以使用.present? 正如sytycs已写的那样。

上一个答案:

如果你有以下情况:item为空,你应该只使用params [:item]而不需要。

 def item_params params[:item].permit(:name) end 

有关require的更多信息,请参阅strong_parameters.rb源代码:

 # Ensures that a parameter is present. If it's present, returns # the parameter at the given +key+, otherwise raises an # ActionController::ParameterMissing error. # # ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person) # # => {"name"=>"Francesco"} # # ActionController::Parameters.new(person: nil).require(:person) # # => ActionController::ParameterMissing: param not found: person # # ActionController::Parameters.new(person: {}).require(:person) # # => ActionController::ParameterMissing: param not found: person def require(key) self[key].presence || raise(ParameterMissing.new(key)) end 

我个人没有切换到强参数,所以我不确定应该如何处理:

  params.require(:item).permit(:name) 

但你可以随时检查项目的存在,例如:

 if params[:item].present? … end