rails select tag,获取nil的未定义方法映射:NilClass

时间:2014-12-27 22:16:09

标签: ruby-on-rails ruby forms

在我的deals_controller.rb中,我在此处定义了新操作

 class DealsController < ApplicationController
    def index
        @deals = Deal.all
    end

    def show
        @deal = Deal.find(params[:id])
    end

    def new
        @vendors = Vendor.all
        # code for select tags on _form view
        @vendor_options = @vendors.map{|v| [v.name, v.id] }

        @items = Item.all
        @item_options = []
        @items.each do |item|
            @item_options << [item.name, item.id]
        end

        @deal = Deal.new
    end

    def create
        @items = Item.all
        @vendors = Vendor.all
        @deal = Deal.new(deal_params)
        if @deal.save
            redirect_to @deal
        else render 'new'
        end
    end

    private
    def deal_params
        params.require(:deal).permit(:item_id, :vendor_id, :price)
    end

end

然后,在我的new.html.erb里面我有

  <p>
    <%= f.label :vendor_id %><br>
    <%= select_tag(:vendor_id, options_for_select(@vendor_options)) %>
  </p>

当我尝试创建一个新的交易时,程序错误

NoMethodError in Deals#create
Showing /Users/andrewkim/wdi/work/app/small_time_grocer/app/views/deals/_form.html.erb where line #21 raised:

undefined method `map' for nil:NilClass

提取的来源来自以下第21行:

 <%= select_tag(:vendor_id, options_for_select(@vendor_options)) %>

我甚至看不到地图的使用位置,或者是否在options_for_select方法中使用了这个地图?

选择标签上的文档对我来说有点神秘,有人能发现我的错误吗?

1 个答案:

答案 0 :(得分:2)

尝试使用collection_select代替select_tag

<%= f.collection_select :vendor_id, @vendors, :id, :name, {include_blank: 'Please Select'}, {class: 'selectpicker chosen-select'} %>

我建议您阅读collection_select