Reputation: 149
I'm currently creating a job board and in my listings/new.html.erb file and I have a section within the form for people to choose a category. The category is its own separate model.
But when I submit the form I get a 'undefined method `map' for nil:NilClass' error.
Below are my models, controllers, and the part of the view which is appropriate. Thank you ahead of time.
_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 => '[email protected]',
: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
end
category.rb
class Category < ApplicationRecord
extend FriendlyId
friendly_id :title, use: :slugged
has_many :listings
end
Edit Log: I updated the listings_controller.rb to include
@categories = Category.all.map{|c| [ c.title, c.id ] }
Upvotes: 0
Views: 70
Reputation: 14900
You're missing this line from your create
action, just make sure it's before any render :new
. This is needed because you're using this in the form in case something fails.
@categories = Category.all.map{|c| [ c.title, c.id ] }
Upvotes: 1