Ruby on rails 讨论中的命名错误#创建

Ruby on rails 讨论中的命名错误#创建,ruby-on-rails,ruby,Ruby On Rails,Ruby,下面是我的文件Users/JBossman/sites/discussions/app/views/discussions/_form.html.erb中的代码摘录,其中第20行引发了此错误未定义的方法“映射”为nil:NilClass enter code here <%= simple_form_for(@discussion) do |f| %> <%= f.error_notification %> <div class="field">

下面是我的文件
Users/JBossman/sites/discussions/app/views/discussions/_form.html.erb
中的代码摘录,其中第20行引发了此错误
未定义的方法“映射”为nil:NilClass

enter code here
<%= simple_form_for(@discussion) do |f| %>
  <%= f.error_notification %>

  <div class="field">
    <div class="control">
      <%= f.input :title, required: true, input_html: { class: 'input' }, wrapper: false, label_html: { class: "label" } %>
    </div>
  </div>

  <div class="field">
    <div class="control">
      <%= f.input :content, required: true, input_html: { class: 'textarea' }, wrapper: false, label_html: { class: "label" } %>
    </div>
  </div>

  <div class="field">
    <label class="label">Channel</label>
    <div class="control has-icons-left">
      <span class="select">
        <%= f.input_field :channel_id, collection:@channels.map { |c| [c.channel, c.id] }, prompt: "Select channel" %>
      </span>
      <span class="icon is-small is-left">
        <i class="fa fa-tag"></i>
      </span>
    </div>
  </div>

  <div class="field">
    <div class="control">
      <%= f.button :submit, class:"button is-info" %>
    </div>
  </div>

<% end %>
在此处输入代码
频道

错误在这里:
@channels.map{| c |[c.channel,c.id]}

您的
@channels
变量为
nil

确保在创建操作中设置了
@channels

看起来像
@channels
nil
。理想情况下,它应该初始化为
[]
空数组


或者,您也可以使用
(@channels | |[]).map{c |[c.channel,c.id]}
来呈现空表单。

更改
@channels.map{c.channel,c.id]
到下面,因为
@channels
未设置(nil)

假设您拥有
频道
模型

一,。如果要显示集合中的所有频道,则可以按如下操作:

Channel.pull(:Channel,:id)

二,。如果要在收藏中显示特定频道,请在
频道
中定义
范围
,如
收藏夹


Channel.favorites.pluck(:Channel,:id)
我通过一点修改修复了一个类似的问题。映射到.collect函数,您可以试一试。

您还没有从action中定义实例变量
@channels
,所以这里您得到了
nil
,调用
map
方法时抛出了错误。是的,我忘了在参数中添加它,因此得到了nil。难道
map
collect
只是彼此的别名吗?