Rails Undefined Method 'model_name'

dennismonsewicz picture dennismonsewicz · Feb 13, 2013 · Viewed 8.8k times · Source

I have the following model:

class Contact
  attr_accessor :name, :emails, :message

  def initialize(attrs = {})
    attrs.each do |k, v|
      self.send "#{k}=", v
    end
  end

  def persisted?
    false
  end
end

I am calling to a contact form in my view like so:

<div class="email_form">
   <%= render 'form' %>
</div>

Here is the controller:

class ShareController < ApplicationController
  layout "marketing_2013"
  respond_to :html, :js

  def index
    @contact = Contact.new
  end
end

Here is the Form:

<%= form_for(@contact) do |f| %>
    <%= f.label :name, "Your Name" %>
    <%= f.text_field :name %>
    <%= f.label :text, "Send to (separate emails with a comma)" %>
    <%= f.text_field :emails %>
    <%= f.label :message, "Email Text" %>
    <%= f.text_area :message %>
    <%= f.submit %>
<% end %>

For some reason I keep getting this error: undefined method model_name for Contact:Class

Any reason why what I have currently wouldn't work?

Answer

Ricardo Valeriano picture Ricardo Valeriano · Feb 13, 2013

Besides the correct route in your config/routes.rb, you will also need these two instructions on your model:

include ActiveModel::Conversion
extend  ActiveModel::Naming

Take a look at this question: form_for without ActiveRecord, form action not updating.

For the route part of these answer, you could add this to your config/routes.rb:

resources :contacts, only: 'create'

This will generate de following route:

contacts POST /contacts(.:format)  contacts#create

Then you can use this action (contacts#create) to handle the form submission.