我正在尝试使用本教程为我的 Rails 3.1.3 应用程序添加联系表。但是最后当我尝试加载我的联系页面时,我得到了错误:
当你没想到时,你有一个 nil 对象!您可能期望有一个 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
为什么我会收到该错误,我该如何解决?谢谢!