我需要在_form.html.erb或控制器中更改什么?

时间:2017-05-30 12:05:20

标签: ruby-on-rails forms controller

我的列表控制器中有这个:

   # GET /listings/new
  def new
    @options_for_select_ary = Subcategory.all.map{|subcategory| subcategory.subcategory_name}
    @listing = Listing.new
  end

  # GET /listings/1/edit
  def edit
    @options_for_select_ary = Subcategory.all.map{|subcategory| subcategory.subcategory_name}
  end

..这在我的_form.html.erb中:

<div class="field">
    <%= f.label :subcategory %>
    <%= f.select :subcategory, options_for_select([@options_for_select_ary]) %>
  </div>

......但是,它只有一个选项可用于下拉列表。

我需要更改的位置或内容才能显示所有子类别?

任何帮助都非常感谢...

1 个答案:

答案 0 :(得分:0)

您无需传递Array中的值。 map总是会返回一个数组。

替换以下

<%= f.select :subcategory, options_for_select([@options_for_select_ary]) %>

<%= f.select :subcategory, options_for_select(@options_for_select_ary) %>

此外,您可能想要更改以下代码

 # GET /listings/new
 def new
   @options_for_select_ary = Subcategory.pluck(:subcategory_name)
   @listing = Listing.new
 end

 # GET /listings/1/edit
 def edit
   @options_for_select_ary = Subcategory.pluck(:subcategory_name)
 end

或者更好地将其移至before_action

before_action :set_options, only: [:new, :edit]

# GET /listings/new
def new
  @listing = Listing.new
end

# GET /listings/1/edit
def edit
end

private

def set_options
  @options_for_select_ary = Subcategory.pluck(:subcategory_name)
end

修改

  

nil的未定义方法`map':NilClass

您可能希望在:update

中添加:createbefore_action
before_action :set_options, only: [:new, :edit, :create, :update]