0

我正在尝试使用本教程为我的 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

为什么我会收到该错误,我该如何解决?谢谢!

4

2 回答 2

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| %>
于 2013-01-24T04:34:45.857 回答
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|
于 2013-01-24T06:07:46.563 回答