2016-04-28 75 views
0

我正在嘗試使用mail_form將聯繫表單放入單頁網頁中。但是,我發現很難按照說明進行操作,因爲他們認爲我特意爲表單提供了一個視圖,但在我的情況下,所有內容都在控制器visitors_controller中。 根據指示,應該找一個像這樣的控制器:Rails,單頁中的聯繫表單

class ContactsController < ApplicationController 
def new 
    @contact = Contact.new 
    end 

def create 
    @contact = Contact.new(params[:contact]) 
    @contact.request = request 
    if @contact.deliver 
     flash.now[:notice] = 'Thank you for your message. We will contact you soon!' 
    else 
     flash.now[:error] = 'Cannot send message.' 
     render :new 
    end 
    end 

end 

而且認爲應該是這樣的:

<%= simple_form_for @contact, html: {class: 'form-horizontal' } do |f| %> 
    <%= f.input :name, :required => true %> 
    <%= f.input :email, :required => true %> 
    <%= f.input :message, :as => :text, :required => true %> 
    <div class= "hidden"> 
     <%= f.input :nickname, :hint => 'Leave this field blank!' %> 
    </div> 
     <%= f.button :submit, 'Send message', :class=> "btn btn-primary" %> 
    <% end %> 

如何實現同我visitors_controller並查看? 控制器目前看起來是這樣的,如果它是重要的

class VisitorsController < ApplicationController 
    def index 
    end 
end 

回答

1

在這一天結束,它只是一種形式,沒有什麼特別的。你只需要告訴POST的形式,並在目標中處理它。默認情況下,它會發布到單獨的控制器,但這不是必需的,只是最簡單的。

要發佈到其他地方,它可以像發佈到特定網址的任何其他表單一樣工作。

首先,您需要創建URL。

的config/routes.rb文件:

resources :visitors do 
    post :contact, on: :collection 
end 

這將路由contact_visitors_path添加到您的應用程序。這是您的表單將POST的目標。

然後,在visitors_controller添加支持這條航線:

def contact 
    @contact = Contact.new(params[:contact]) 
    @contact.request = request 
    if @contact.deliver 
    flash.now[:notice] = 'Thank you for your message. We will contact you soon!' 
    redirect_to visitors_path # Go back to the index page 
    else 
    flash.now[:error] = 'Cannot send message.' 
    render :index # Instead of :new, as we submit from :index 
    end 
end 

接下來,添加支持這種形式的索引頁(顯示錶單的頁面,比如上例中的「新」):

def index 
    @contact = Contact.new 
end 

最後,只需要告訴表單發佈的位置。

= simple_form_for @contact, url: contact_visitors_path, html: {class: 'form-horizontal' } 

現在,窗體指向您的visitors_controller,並由您的自定義方法處理。其他一切工作都一樣。

+0

謝謝!有效 –