【问题标题】:Rails select_tag undefined method `map' for nil:NilClass用于 nil:NilClass 的 Rails select_tag 未定义方法“map”
【发布时间】:2016-11-07 14:00:04
【问题描述】:

我有我的问题,有点解决了,但我认为它有点笨拙,所以希望得到一个更好的方法,以及更好地理解这里发生了什么。

_form.html.erb:

 <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select one!") %>

products_controller.rb:

def new
  @product = Product.new
  @categories = Category.all.map { |c| [ c.name, c.id ] }
end

如果用户在未选择任何select_tag 选项的情况下提交表单,则会收到undefined method 'map' for nil:NilClass 错误。

我知道这是因为我的@categoriesnil,但我不知道如何避免这种情况..?

我的最终解决方案,这是有效的:

<%= select_tag(:category_id, options_for_select(@categories || Category.all.map { |c| [ c.name, c.id ] }), :prompt => "Select one!") %>

但我觉得有更好的方法。另外我认为,通过使用:selected 分配默认的select_tag 值可能也可以,但我无法根据我对Ruby 语法的了解来实现它...

【问题讨论】:

  • 当您提交表单时,create 方法被执行,如果 @product.save 返回 false,请确保在 create 方法中初始化 @categories
  • 哦,那很好。感谢您的回答。我添加了if @product.save == false @categories = Category.all.map{|c| [ c.name, c.id ] } end 来创建动作,看起来效果很好。很遗憾我无法将您的评论标记为答案...
  • @dnsh 评论工作正常,但来自@SnehaT 的答案是更好的方法,因为它消除了对@categories 的需要......最好你应该有尽可能少的实例变量可以查看,理想情况下只有一个。

标签: ruby-on-rails form-for


【解决方案1】:

请尝试这种 select_tag 方式:

select_tag(:category_id, options_from_collection_for_select(Category.all, :id, :name), include_blank: "Select Category")

如果您遇到任何问题,请告诉我..

【讨论】:

  • 哦,它甚至更好。我认为避免额外的循环会更好。谢谢!
【解决方案2】:

是的,您可以使用辅助方法而不是在每个视图中使用 Category.all

def categories
  Category.all.map { |c| [ c.name, c.id ] }
end

并在视图中使用它

<%= select_tag(:category_id,
               options_for_select(categories), 
               include_blank: "Select Category") %>

【讨论】:

    【解决方案3】:

    你也可以试试这样的。

    products_controller.rb:

    class ProductsController < ApplicationController
      before_action :set_select_collections, only: [:edit, :update, :new, :create]
    
      private
        def set_select_collections
          @categories = Category.all.map { |c| [ c.name, c.id ] }
        end
    end
    

    之后你应该可以使用了:

    _form.html.erb:

    &lt;%= select_tag(:category_id, options_for_select(@categories), include_blank: "Select one!") %&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多