Reputation: 39
Every time I submit the form I get this error: undefined method `each' for nil:NilClass
. If everything is correct I can submit the form without any problems, but when there is one thing missing it gives me that error. The error sends me to this line:
views/users/new.html.haml
- @subscriptions.each do |fbs|
= fb.radio_button :subscription_id, fbs.id, class: 'radiobtn', required: true
controllers/users_controller.rb
def new
@user = Users::Business.new
@subscriptions = Businesses::Subscription.all
end
def create
@user = Users::Business.new(user_params)
if @user.save
sign_in(@user)
else
render :new
end
end
Upvotes: 0
Views: 436
Reputation: 5204
Assigns subscriptions in a create action too:
before_filter :set_subscriptions, only: %w(new create) #for edit and update if needed
private
def set_subscriptions
@subscriptions = Businesses::Subscription.all
end
Or add @subscriptions = Businesses::Subscription.all
directly to create
action after the saving is failed and you re-render new
form.
Upvotes: 2
Reputation: 1085
It is happening because there is no value persisted with that model .
You can check the data into the rails console
like ,
$rails console
> Businesses::Subscription.count
And if you see that there is no data then you can write a if ... end
block to check for null value and handle it.
Upvotes: 0