Zack Shapiro
Zack Shapiro

Reputation: 6998

Trying to create an email signup form but get undefined method `model_name' for NilClass:Class

I've been staring at this for a while and Google hasn't helped much so I'm turning to you guys for help. This should be a pretty simple fix.

The goal of the code is to take an email address from a sign up field and place it in the database.

I think most of what I need is there but I'm getting this error:

undefined method model_name for NilClass:Class

My home.html.erb file contains the following:

    <%= form_for(@signup) do |f| %>
        <div class="field">
            <%= f.label :email %><br />
            <%= f.text_field :email %>
        </div>

        <div class="actions">
            <%= f.submit "Enter" %>
        </div>
    <% end %>

The model contains this:

class Signup < ActiveRecord::Base

  attr_accessible :email
     email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
     validates(:email, :presence => true,
                    :length => {:maxiumum => 40},
                    :format => {:with => email_regex})

end

The controller contains:

class SignupController < ApplicationController

  def show
  end

  def new
    @signup = Signup.new
  end

  def create
    @signup = Signup.new(params[:id])
    if @signup.save
    else
      render 'new'
    end
  end

end

Upvotes: 0

Views: 191

Answers (2)

Mischa
Mischa

Reputation: 43298

Add this to the home action in the pages controller:

@signup = Signup.new

The reason for the error is that you are using @signup in your form, but you didn't define it in your show controller action.

Upvotes: 1

miked
miked

Reputation: 4499

The problem is most likely because of an instance variable that you're using in your form_for not being set to an ActiveRecord object. It appears that you are setting it correctly in your "new" action, but it's not clear that you're rendering the correct template since you mention the form being in "home.html.erb"?

Either way, ensure that whatever you're using in the form_for is set to a valid ActiveRecord object and your problem may be solved.

In addition, you may want to change your create action to use all the params from the form:

@signup = Signup.new(params[:signup])

Upvotes: 2

Related Questions