Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 744
dennismonsewicz Avatar asked Feb 13 '13 19:02

dennismonsewicz


2 Answers

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.

like image 98
23 revs, 14 users 49% Avatar answered Nov 18 '22 17:11

23 revs, 14 users 49%


add include ActiveModel::Model to your Contact file

like image 1
Marat Avatar answered Nov 18 '22 17:11

Marat