【问题标题】:Rails Undefined Method 'model_name'Rails未定义方法'model_name'
【发布时间】:2013-02-13 19:44:58
【问题描述】:

我有以下型号:

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

在我看来,我正在调用一个联系表单,如下所示:

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

这里是控制器:

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

  def index
    @contact = Contact.new
  end
end

这是表格:

<%= 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 %>

由于某种原因,我不断收到此错误: undefined method model_name for Contact:Class

我目前所拥有的东西不起作用的任何原因?

【问题讨论】:

标签: ruby-on-rails-3 activemodel


【解决方案1】:

除了 config/routes.rb 中的正确路线外,您的模型还需要以下两条说明:

include ActiveModel::Conversion
extend  ActiveModel::Naming

看看这个问题:form_for without ActiveRecord, form action not updating

对于这些答案的route 部分,您可以将其添加到您的 config/routes.rb:

resources :contacts, only: 'create'

这将生成以下路线:

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

然后您可以使用此操作(contacts#create)来处理表单提交。

【讨论】:

  • 我错过了您列出的两条说明。谢谢!
【解决方案2】:

include ActiveModel::Model 添加到您的联系人文件中

【讨论】:

    【解决方案3】:

    你的路线可能不会去你认为它要去的地方,因此@contact 可能是空的

    运行“rake routes”并检查新路径..如果您使用默认值,则路由是

    new_contact_path.. 并且 erb 应该在文件中:app/views/contacts/new.html.erb

      def new
        @contact = Contact.new
      end
    

    【讨论】:

      猜你喜欢
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多