Rails 4:如何处理未选择任何内容的提交表单? [英] Rails 4: How do I handle a submitted form where nothing was selected?

查看:44
本文介绍了Rails 4:如何处理未选择任何内容的提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果标题有点混乱,请见谅.我有一个 Item 的表单,其字段为 name.有一个文本字段,用户可以在其中输入名称并提交.但是如果用户没有输入任何内容并点击提交,Rails 会给我一个 param not found: item 错误,我不知道该找谁解决这个问题.

Sorry if the title is a little confusing. I have a form for an Item with the field name. There's a text field where the user can input a name and submit it. But if the user doesn't type in anything and hits submit, Rails gives me a param not found: item error, and I'm not sure who to get around this.

items_controller.rb

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

app/views/items/new.html.haml

app/views/items/new.html.haml

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

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

The params.require(:item) part is what is causing the error. What the convention for handling the error when params[:item] isn't present?

推荐答案

答案已经晚了,但我仍然会为其他人写.如 rails guides 中所述,您需要在强参数中使用 fetch 而不是 require,如果没有任何内容作为输入传递,则通过使用 fetch 您可以提供默认值.类似的东西:

It's late for an answer but i'll still write it for someone else. As stated in rails guides you need to use fetch instead of require in strong parameters, by using fetch you can provide a default value if nothing is passed as input. Something like:

params.fetch(:resource, {}) 

这篇关于Rails 4:如何处理未选择任何内容的提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆