简体   繁体   中英

Ruby on rails - undefined method `each' for nil:NilClass

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM