rails select标签,获取nil:NilClass的未定义方法映射 [英] rails select tag, getting undefined method map for nil:NilClass

查看:88
本文介绍了rails select标签,获取nil:NilClass的未定义方法映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my deals_controller.rb i have the new action defined here

 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中,我拥有

Then, inside my new.html.erb i have

  <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行:

The extracted source is from line 21 below:

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

我什至看不到地图在哪里使用,或者在options_for_select方法中固有地使用了地图?

I don't even see where map is being used, or is that inherently being used in the options_for_select method?

select标签上的文档对我来说有点神秘,有人可以发现我的错误吗?

The documentation on the select tag is a little cryptic to me, can anyone spot my error?

推荐答案

尝试使用 collection_select 代替 select_tag :

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

我建议阅读有关 collection_select

这篇关于rails select标签,获取nil:NilClass的未定义方法映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆