Jake
Jake

Reputation: 1186

Object.errors in Ruby on Rails not working

I have a form error partial that raises a NoMethodError in Users#new. It says "undefined method errors for nil:NilClass

This is the partial I am calling via: <%= render 'shared/error_messages', object: f.object %>

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

The new.html.erb for users:

<%= simple_form_for :user, url: register_path do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <%= f.input :username, label: false, placeholder: "Username (maximum: 12 characters)", class: "form-control" %>
  <%= f.input :first_last_name, label: false, placeholder: "First & Last Name", class: "form-control" %>
  <%= f.input :email, label: false, placeholder: "Email Address", class: "form-control" %>
  <%= f.input :password, label: false, placeholder: "Create a Password (minimum: 6 characters)", class: "form-control" %>
  <%= f.button :submit, "Create an Account!", class: "submit btn btn-block btn-success" %>
<% end %>

users_controller:

before_action :logged_in_user, only: [:edit, :update, :show]
before_action :correct_user,   only: [:edit, :update, :show]
before_action :admin_user,     only: :destroy

def new
  @title = 'Register';
  @user = User.new;
end

def create
  @user = User.new(user_params)
  if @user.save
    @user.send_activation_email
    flash[:info] = "Please check your email to activate your account."
    redirect_to root_url
  else
    render 'new'
  end
end

  private

def user_params
  params.require(:user).permit(:username, :first_last_name, :email, :password)
end

# Before filters

# Confirms the correct user.
def correct_user
  @user = User.find(params[:id])
  redirect_to(root_url) unless current_user?(@user)
end

# Confirms an admin user.
def admin_user
  redirect_to(root_url) unless current_user.admin?
end

I don't really understand why this wouldn't be working, Thanks for the help!

Upvotes: 2

Views: 787

Answers (1)

Julien
Julien

Reputation: 2329

Change the way you are opening the form to this (instead of a symbol pass the object you created in the new action):

<%= simple_form_for @user, url: register_path do |f| %>

Upvotes: 1

Related Questions