[英]My app is throwing a random undefined method `map' for nil:NilClass error
我目前正在创建工作板,并且在我的listings / new.html.erb文件中,并且表单中有一个部分供人们选择类别。 类别是其自己的单独模型。
但是当我提交表单时,我得到了一个nil:NilClass错误的“未定义方法`map”。
以下是我的模型,控制器和适当的视图部分。 提前谢谢你。
_form.html.erb
<div class="form-group">
<h4>Job Category:</h4>
<%= form.select(:category_id, options_for_select(@categories)) %>
</div>
listings_controller.rb
def new
@listing = Listing.new
@categories = Category.all.map{|c| [ c.title, c.id ] }
end
def create
@categories = Category.all.map{|c| [ c.title, c.id ] }
@listing = Listing.new(listing_params)
@listing.category_id = params[:category_id]
charge_error = nil
if @listing.valid?
begin
customer = Stripe::Customer.create(
:email => 'example@stripe.com',
:card => params[:stripeToken])
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => 150,
:description => 'Job Posting via Remote Business Jobs',
:currency => 'usd')
rescue Stripe::CardError => e
charge_error = e.message
end
if charge_error
flash[:error] = charge_error
render :new
else
@listing.save
redirect_to @listing
end
else
flash[:error] = 'one or more errors in your orders'
render :new
end
end
def listing_params
params.require(:listing).permit(:title, :body, :apply_link,
:company_link, :employment_type, :company, :salary_range,
:category_id,
:slug, :hq)
end
listing.rb
class Listing < ApplicationRecord
extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :category
结束
category.rb
class Category < ApplicationRecord
extend FriendlyId
friendly_id :title, use: :slugged
has_many :listings
end
编辑日志 :我更新了listings_controller.rb,使其包含
@categories = Category.all.map{|c| [ c.title, c.id ] }
您在create
操作中缺少此行,只需确保它在任何render :new
之前。 这是必需的,因为如果出现故障,您将以表格的形式使用它。
@categories = Category.all.map{|c| [ c.title, c.id ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.