1

我正在尝试为基于为模型选择的记录(称为“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

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

4

1 回答 1

0

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
于 2012-09-02T02:33:58.573 回答