Rails Undefined Method 'model_name'
Asked Answered
E

3

7

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?

Extinctive answered 13/2, 2013 at 19:44 Comment(1)
This has been answered in #10824236Silberman
W
14

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.

Woodberry answered 13/2, 2013 at 20:9 Comment(1)
I was missing the the two instructions you listed. Thanks!Extinctive
M
2

add include ActiveModel::Model to your Contact file

Maggs answered 7/11, 2019 at 13:16 Comment(0)
S
0

your route probably doesn't go where you think it's going and therefore @contact is probably nill

run "rake routes" and check the new path.. if you are using defaults, the route is

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

  def new
    @contact = Contact.new
  end

Shealy answered 13/2, 2013 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.