我正在尝试使用this tutorial为我的Rails 3.1.3应用程序添加联系表单。但是当我尝试加载我的联系页面时,我收到错误:
当你没想到它时,你有一个零对象! 您可能期望一个Array实例。 在评估nil。[]
时发生错误它表示它出现在new.html.haml页面上此代码块的第1行:
= form_for @message, :url => { :action=>"new", :controller=>"contact"} do |form|
%fieldset.fields
.field
= form.label :name
= form.text_field :name
.field
= form.label :email
= form.text_field :email
.field
= form.label :body
= form.text_area :body
%fieldset.actions
= form.submit "Send"
我的控制器看起来像这样:
class ContactController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
NotificationsMailer.new_message(@message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
模型看起来像这样:
class Message < ActiveRecord::Base
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :body
validates :name, :email, :body, :presence => true
validates :email, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
为什么我会收到该错误,如何解决?谢谢!
答案 0 :(得分:1)
你是否在教程中添加了路由?
match 'contact' => 'contact#new', :as => 'contact', :via => :get
match 'contact' => 'contact#create', :as => 'contact', :via => :post
除了你可以在你的形式使用
<%= form_for @message, :url => contact_path do |form| %>
答案 1 :(得分:0)
如果您使用单独的表单进行新操作和编辑操作,可以在new.html.haml
中使用 = form_for :message, :url => { :action=>"new", :controller=>"contact"} do |form|
或
= form_for :message, @message, :url => { :action=>"new", :controller=>"contact"} do |form|