2016-04-28 74 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

谢谢!有效 –