【问题标题】:What do I need to change in my _form.html.erb or controller?我需要在我的 _form.html.erb 或控制器中进行哪些更改?
【发布时间】:2017-05-30 12:05:19
【问题描述】:

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

   # 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>

...它有效,但是,它在下拉菜单中只有一个可用选项。

我需要更改哪些地方或哪些内容才能显示所有子类别?

非常感谢任何帮助...

【问题讨论】:

  • options_for_select(@options_for_select_ary)
  • 这个成功了,如下!

标签: ruby-on-rails forms controller


【解决方案1】:

您不需要传递 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:NilClass 的未定义方法 `map'

您可能想在before_action 中添加:update:create

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

【讨论】:

  • 我现在得到了 nil:NilClass 的未定义方法 `map' 你的意思是?点击提取的源代码(第 29 行附近):27 28 29 30 31 32
    模板包含的痕迹:app/views/listings/new.html.erb
  • 啊。您可能还想添加[:update, :create]
  • 因为如果表单中有错误,它会从createupdate 操作呈现newedit 模板
猜你喜欢
相关资源
最近更新 更多
热门标签