0

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
3
  • Submitting the form will call the controller's create action, how does it look like? I suspect that you call render "new" and don't set @subscriptions. Commented Dec 15, 2016 at 11:26
  • did you have some deprecated warnings about TopLevel constant in rails console? if yes, try to use @subscriptions = ::Businesses::Subscription.all Commented Dec 15, 2016 at 11:27
  • Thank's for the edit. Like I suspected: you render the new template from within create but you don't set @subscriptions as required by the template. Commented Dec 15, 2016 at 11:40

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Businesses::Subscription.all never returns nil.
i agree with Stefan. It returns empty relation, not nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.