Rails Undefined Method 'model_name'

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 refer to the contact form in my view like this:

 <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 I wasn’t working right now?

+4
source share
2 answers

In addition to the correct route in your config / routes.rb, you will also need the following two instructions for your model:

 include ActiveModel::Conversion extend ActiveModel::Naming 

Take a look at this question: form_for without ActiveRecord, the form action is not updated .

For the route response part, you can add this to your config / routes.rb:

 resources :contacts, only: 'create' 

This will create the following route:

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

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

+11
source

your route probably won’t go the way you think and therefore @contact probably nill

start the "rake routes" and check the new path. If you use the default settings, the route

new_contact_path .. and erb should be in the file: app / views / contacts / new.html.erb

 def new @contact = Contact.new end 
0
source

All Articles