导轨形式不会导致错误

导轨形式不会导致错误

问题描述:

我一直在研究导轨形式,并认为我搞砸了一些东西,但不能把我的手指放在什么。导轨形式不会导致错误

给出一个概述。我在底部创建了一个带有联系表单的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添加到主控制器 –

您正在创建新的方法联系的一个实例,并调用具有的form_for该实例上index.html.erb这就是为什么你得到@contact,只需将此代码@contact = Contact.new索引方法/动作,其中您实际调用与联系人实例的窗体。