2013-01-24 13 views
0

我想添加一個聯繫表格爲我的Rails 3.1.3應用程序使用this tutorial。然而,最後當我嘗試加載我的聯繫頁面時,出現錯誤:沒有對象,當你不希望它的聯繫form_for

當你沒有想到它時,你有一個零對象! 您可能預期了Array的一個實例。在評估零發生 錯誤[]

它說,它發生在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{[email protected]+\..+} }, :allow_blank => true 

    def initialize(attributes = {}) 
    attributes.each do |name, value| 
     send("#{name}=", value) 
    end 
    end 

    def persisted? 
    false 
    end 

end 

瓦我會得到那個錯誤,我該如何解決它?謝謝!

+0

是您的HAML縮進正確上面鍵入?它看起來像'%fieldset.fields'不是'form_for'的子代 –

+0

是的,那只是一個複製/粘貼錯誤。據我所知,所有內容都被正確縮進。 – Anoel

回答

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| %> 
+0

是的,我有這個:match'contact'=>'contact#new',:as =>'contact',:via =>:獲得 匹配'contact'=>'contact#create',:as => 'contact',:via =>:post。我試着爲url做contact_path,但它給了我同樣的錯誤。當我做耙路線時,contact_path不在那裏,所以我拿出來確定。 – Anoel

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| 
+0

好吧,我試過(沒有編輯),我得到了同樣的錯誤,但現在在第5行(表單文本字段名稱)。有什麼辦法解決這個問題嗎? – Anoel

+0

通過一些rails文檔。他們建議使用 = form_for:message,@message:url => {:action =>「new」,:controller =>「contact」} do | form | – Subramaniam

+0

這給了我第一行「語法錯誤,意外」:',「。應該有@message和:url之間的東西嗎?我搜索了rails文檔並找不到任何有關它的信息。 – Anoel

相關問題