【问题标题】:rails form select multiple gives empty first valuerails form select multiple给出空的第一个值
【发布时间】:2015-09-16 00:11:03
【问题描述】:

我已经定义了 Meals 和 Recipes 之间的 has_and_belongs_to_many 关联。在 Meals create 表单中,我使用选择来填充食谱。

<%= f.select :recipes, Recipe.all.collect { |x| [x.name, x.id]}, {}, :multiple => true %>

但是结果集的第一个值是 nil。

"recipes"=>["", "2", "7"]

如何消除空/nil 值?

【问题讨论】:

  • params[:recipes].reject(&amp;:blank?)
  • 控制器里有吗?如果是这样,哪一个,膳食或食谱?
  • 无论您从何处获得该阵列。只需拨打.reject(&amp;:blank?)就可以了。
  • 我将它添加到发生错误的控制器中并且它不起作用。 def create meal_params[:recipes].reject(&amp;:blank?) @meal = Meal.new(meal_params) respond_to do |format| if @meal.save format.html { redirect_to @meal, notice: 'Meal was successfully created.' } format.json { render :show, status: :created, location: @meal } else format.html { render :new } format.json { render json: @meal.errors, status: :unprocessable_entity } end end end
  • .reject(&amp;:blank?) 不会影响您调用它的对象,它只是将结果返回给您。因此,您要么需要将结果存储在一个变量中并使用它,要么使用#reject:(meal_params[:recipes].reject!(&amp;:blank?)) 的爆炸版本。

标签: ruby-on-rails forms


【解决方案1】:

对我来说设置:include_hidden =&gt; false 是有效的

<%= f.select :recipes, Recipe.all.collect { |x| [x.name, x.id]}, {:include_hidden => false}, :multiple => true %>

【讨论】:

  • 也为我工作。谢谢!
  • here 上有一些文档。
【解决方案2】:

你可以通过:include_blank =&gt; false拒绝空白选项

<%= f.select :recipes, Recipe.all.collect { |x| [x.name, x.id]}, {:include_blank => false}, :multiple => true %>

你可以设置如下提示

<%= f.select :recipes, Recipe.all.collect { |x| [x.name, x.id]}, {:include_blank => "Please Select"}, :multiple => true %>

【讨论】:

  • 问题不在于选择框有空白。单击提交按钮后,结果中会出现空/空白/无。我想删除或阻止结果中的空白 "recipes"=>["", "2", "7"]
  • 我添加了 include_hidden,但它仍然不起作用: true, :include_hidden => false %>
  • 它应该不会导致保存或更新数据的问题,我有时在我的参数中发现这种类型的空元素,但没有出现问题。你有什么错误吗?如果发现任何错误,请发布,然后我会尽力帮助您解决错误。
  • 这是错误:Recipe(#81240384) expected, got String(#3158916) Rails.root: C:/Users/Michael/rails/foodian Application Trace |框架跟踪 | Full Trace app/controllers/meals_controller.rb:28:in `create' 请求参数:{"utf8"=>"✓", "authenticity_token"=>"95U7L0xfW+UOXkgGFY6FPSkfJP70gV0lk2c6cnGwaxG2PALRUbZh3E4iNLf0Dn8R3tC1Z2SkcZXqdq48ltNSOw==", "=>"试餐", "description"=>"试试这个", "recipes"=>["", "2", "7"]}, "commit"=>"创建餐"}跨度>
  • 您的model associations 之间似乎不匹配尝试修复它们,这可以帮助您stackoverflow.com/questions/5716412/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
相关资源
最近更新 更多