我是铁杆新手。我正在尝试创建一个包含姓名,电子邮件,电话号码和消息字段的表单。当我点击链接到表单的按钮时,我收到错误:
NilClass的未定义方法`model_name':Class
以下是_form.html.erb页面的代码:
<%= form_for(@contact) do |f| %>
<% if @contact.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2>
<ul>
<% @contact.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="col-md-4">
<div class="form-group">
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, :class=>"form-control", :placeholder=>"Enter Your Name" %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email, :class=>"form-control", :placeholder=>"Enter Your Email"%>
</div>
<div class="field">
<%= f.label :phone %><br />
<%= f.text_field :phone, :class=>"form-control", :placeholder=>"Enter Your Phone Number"%>
</div>
</div>
</div>
<div class = "col-md-8">
<div class="form-group">
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description, :class=>"form-control", :size=>"20x5", :placeholder=>"Enter Your Message"%>
</div>
</div>
</div>
<div class="actions">
<%= f.submit "Submit", :class=> "button1"%>
</div>
<% end %>
这是contacts_controller.rb的代码:
class ContactsController < ApplicationController
# GET /contacts/new
# GET /contacts/new.xml
def new
@contact = Contact.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @contact }
end
end
# POST /contacts
# POST /contacts.xml
def create
@contact = Contact.new(params[:contact])
respond_to do |format|
if @contact.save
format.html { redirect_to(root_path, :notice => 'Thank you for contacting us. We will get back to you shortly.') }
format.xml { render :xml => @contact, :status => :created, :location => @contact }
else
format.html { render :action => "new" }
format.xml { render :xml => @contact.errors, :status => :unprocessable_entity }
end
end
end
end
另外,我在resources :contacts
文件中添加了routes.rb
请帮我理解这里的问题。 感谢。
答案 0 :(得分:0)
请将routes.rb
修改为:
使用
resources :contacts
而不是
resources: contacts
答案 1 :(得分:0)
您在部分中调用@contact
- 它应该是一个本地var,在您调用partial时定义:
<%= render partial: "form", locals: { contact: @contact } %>
......然后......
#_form.html.erb
<%= form_for contact do ...
model_name
错误来自form_for
- 当它占用一个对象时,它会查找model_name
属性,以填充路径等。
由于您与NilClass:Class
一起收到错误,因此表明您的@contact
变量未定义。
以上是我的建议;你不应该在你的部分中呼叫@instance_variables
。