2016-05-16 92 views
-3

我一直在研究導軌形式,並認爲我搞砸了一些東西,但不能把我的手指放在什麼。導軌形式不會導致錯誤

給出一個概述。我在底部創建了一個帶有聯繫表單的1頁網站。我已經四處尋找類似的問題,他們似乎有另一個控制器的另一頁上的聯繫表單,所以無法找到我的答案。我知道我錯過了一些東西,但無法弄清楚什麼。

我得到這一條錯誤

First argument in form cannot contain nil or be empty 

main_controller.rb如下

class MainController < ApplicationController 

    def new 
    @contact = Contact.new 
    end 

    def create 
    @contact = Contact.new(contact_params) 
    @contact.request = request 
    if @contact.deliver 
     redirect_to thank_you_path 
    else 
     flash.now[:error] = 'Cannot send message.' 
     render :index 
    end 
    end 

    private 

    def contact_params 
    params.require(:contact).permit(:name, :email, :phone, :message) 
    end 

end 

contact.rb

class Contact < MailForm::Base 
    attribute :name,  :validate => true 
    attribute :email,  :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i 
    attribute :phone,  :validate => true 
    attribute :message, :validate => true 

    def headers 
    { 
     subject: "Quote Form", 
     to: "[email protected]", 
     from: %("#{name}" <#{email}>) 
    } 
    end 

end 

index.html.erb

<%= bootstrap_form_for(@contact, layout: :horizontal, label_col: "col-sm-2", control_col: "col-sm-10") do |f| %> 
form template here 
<% end %> 

路線/ RB

Rails.application.routes.draw do 
    resources :main, only: [:new, :create] 
    root 'main#index' 
    get '/thank-you'   => 'main#thank-you' 
end 
+0

您沒有在控制器的索引操作中定義的@ @ contact。 –

+0

您需要在您的索引操作中啓動'@contact',因爲index.html.erb上的'@contact'爲零,或者用您的表單中的Contact.new替換'@contact' –

+0

@ j-dexx我該如何解決這個問題?我試圖將其作爲def index添加到主控制器 –

回答

0

您正在創建新的方法聯繫的一個實例,並調用具有的form_for該實例上index.html.erb這就是爲什麼你得到@contact,只需將此代碼@contact = Contact.new索引方法/動作,其中您實際調用與聯繫人實例的窗體。