Rails undefined 方法 'map' for nil:NilClass



我正试图为表单创建一个选择字段,该字段根据为模型选择的记录进行选择(称为"Cancellation_Reasons")。

在我的模型中称为取消:

<%= form_for(@cancellation do |f| %>
    <%= options_from_collection_for_select(@cancellation_reasons, :id, :name) %>
<% end %>

在Cancellation_Controller:中

def new
  @cancellation = Cancellation.new
  @cancellation_reasons = CancellationReason.find(1)    
  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @trade }
  end
end

当我在Rails控制台中运行CancellationReason.find(1)时,它会找到记录,所以@cancel_reasons不是nil。我认为这可能是我使用选择助手的方式(我已经尝试过使用它们,但即使在阅读了RailsGuide和Railsneneneba API文档后,我也不太确定该使用哪一个)。

options_from_collection_for_select期望一个集合(即使它是1的集合)。因此,将代码更改为:

def new
  @cancellation = Cancellation.new
  @cancellation_reasons = CancellationReason.all
  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @trade }
  end
end

相关内容

最新更新