2017-02-03 39 views
0

我有一個主要使用Rails構建的靜態網站。每個頁面都由頁面控制器管理。我在每個頁面的底部都有一個聯繫表單。我正在使用mail_form。每個表單都需要一個新的ContactForm對象。我已經定義了聯繫表單。這是它的模式:其他控制器中的實例變量 - Rails

ActiveRecord::Schema.define(version: 20170130205713) do 

create_table "contact_forms", force: :cascade do |t| 
    t.string "name" 
    t.string "email" 
    t.string "message" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

end 

這裏是控制器:

class ContactFormsController < ApplicationController 
def new 
    @contact_form = ContactForm.new 
end 

def create 
    begin 
    @contact_form = ContactForm.new(params[:contact_form]) 
    @contact_form.request = request 
    if @contact_form.deliver 
     flash.now[:notice] = 'Thank you for your message!' 
    else 
     render :new 
    end 
    rescue ScriptError 
    flash[:error] = 'Sorry, this message appears to be spam and was not delivered.' 
    end 
end 
end 

我希望能夠在每個頁面控制器的視圖創建的ContactForm對象的新實例。當我嘗試在頁面控制器的主視圖定義

@contact_form = ContactForm.new 

,例如,我得到這個錯誤:

NoMethodError in PagesController#home 
undefined method `type' for {:validate=>true}:Hash 

有沒有辦法做到這一點沒有我的所有操作遷入ContactForm控制器?

+0

的錯誤是在'PagesController'但你只給我們看了'ContactFormsController' ... – trueinViso

回答

0

如果我正確地得到你,你需要有一個contact_form的實例變量,可以在每個頁面中使用,因爲每個頁面的底部都有聯繫表單。

您可以在ApplicationController中創建一個私有方法,並將其用作任何控制器中的'before_action',其操作需要該對象存在。類似下面

添加以下行ApplicationController.rb

private 
def init_contact_form 
    @contact_form ||= ContactForm.new 
end 

,您所需要的是@contact_form對象控制器下面使用。 下方添加在您的PagesController.rb

before_action :init_contact_form 
相關問題