1

导轨 3.2

我使用Mail_form gem(来自 plataformatec)为我的网站创建一个简单的“联系我们”表单。当点击“发送”时,我收到一个路由错误,上面写着:

Routing Error
No route matches [POST] "/contactus"
Try running rake routes for more information on available routes.

我有一个非常简单的设置,但我是 Rails 的新手,并且仍在掌握它。我只希望表单向某个电子邮件地址发送电子邮件......没有别的。我知道问题出在 routes.rb 但我一直在摆弄这个问题很长时间我就是不知道出了什么问题。我从来没有为 Rails 错误如此挣扎过。请帮忙!

“页面”模型:app/models/pages.rb

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

  def headers
    :subject => "#{page_title}",
    :to => "careers@example.com",
    :from => %("#{name}" <#{email}>)
  end
end

“页面”控制器:app/controllers/pages_controller.rb

class PagesController < ApplicationController
    respond_to :html

    def index
    end

    def create
        page = Page.new(params[:contact_form])
        if page.deliver
          redirect_to contactus_path, :notice => 'Email has been sent.'
        else
          redirect_to contactus_path, :notice => 'Email could not be sent.'
        end
    end
end

表单部分:app/views/pages/_form.html.erb

<%= simple_form_for :contact_form, url: contactus_path, method: :post do |f| %>

<div>
    <%= f.input :name %>
    <%= f.input :email, label: 'Email address' %>
    <%= f.input :page_title, label: 'Title' %>
    <%= f.input :page_body, label: 'Your message', as: :text %>
</div>

<div class="form-actions">
    <%= f.button :submit, label: 'Send', as: :text %>
</div>

查看(称为contactus):app/views/pages/contactus.html.erb

<body>
    <div>
        <h2 class="centeralign text-info">Contact Us</h2>
    </div>
    <div class="container centeralign">
            <%= render 'form' %>
    </div>
            <h2>We'd love to hear from you! </h2><br /><h4 class="muted">Send us a message and we'll get back to you as soon as possible</h4>
    </div>
</div>
</body>

路由.rb

Example::Application.routes.draw do
  resources :pages
  root to: 'pages#index', as: :home
  get 'contactus', to: 'pages#contactus', as: :contactus
  get 'services', to: 'pages#services', as: :services
4

1 回答 1

3

您的 routes.rb 文件没有路线POST /contactus You've got a route for GET /contactusbut no POST,所以 rails 说的是正确的。

只需添加类似

post 'contactus', to: 'controller#action'

使用您需要调用的任何控制器和操作。或者,如果您尝试create在页面控制器中调用操作,那么您的问题是您添加resources :pages到路由的位置,您实际上已经创建了路由

post 'pages'

因此,在这种情况下,我会将您的simple_form_for网址更改为发布到那里。尝试使用

simple_form_for :contact_form, url: pages_path, method: :post do

反而。如果pages_path不起作用,那么只需rake routes在控制台中运行,您将看到您拥有的所有路线的列表,包括它们的名称。然后只需选择您需要的那个:)

于 2013-08-01T07:29:52.523 回答