为什么我会收到“没有路线匹配帖子”?

时间:2013-07-30 01:18:48

标签: ruby-on-rails ruby

我不太清楚为什么会收到此错误:

Routing Error
No route matches [POST] "/transactions/new"

这是我的配置文件:

TwerkApp::Application.routes.draw do
  get "transactions/new"
  resources :transactions

这是我的控制者:

class TransactionsController < ApplicationController
  def new
    @transaction = Transaction.new(current_user.email, 100.0, params[:transaction])
  end

  def create
    @transaction = Transaction.new(current_user.email, 100.0, params[:transaction])
    if @transaction.charge
      flash[:success] = 'Thanks for the moolah!'
      redirect_to root_path
    else
      flash[:error] = @transaction.errors.first
      render :new
    end
  end
end

这是新的交易形式:

= form_for :transaction do |f|
  = label_tag :card_number, "Credit Card Number"
  = text_field_tag :card_number, nil, name: nil, :value => "4111111111111111", class: "cc-number"
  %p
  = label_tag :card_code, "Security Code on Card (CVV)"
  = text_field_tag :card_code, nil, name: nil, :value => "123", class: "cc-csc"
  %p
  = label_tag :card_month, "Card Expiration"
  = select_month nil, {add_month_numbers: true}, {name: nil, class: "cc-em"}
  = select_year Date.new(2020), {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, class: "cc-ey"}
  %br
  = f.submit

耙路线:

      transactions GET    /transactions(.:format)              transactions#index
                   POST   /transactions(.:format)              transactions#create
   new_transaction GET    /transactions/new(.:format)          transactions#new
  edit_transaction GET    /transactions/:id/edit(.:format)     transactions#edit
       transaction GET    /transactions/:id(.:format)          transactions#show
                   PUT    /transactions/:id(.:format)          transactions#update
                   DELETE /transactions/:id(.:format)          transactions#destroy

有没有人有任何想法?

2 个答案:

答案 0 :(得分:1)

  1. get "transactions/new"已生成此路线时,我不知道您的路线中有resources :transactions的原因。
  2. 没有[POST] "/transactions/new",只有一个GET /transactions/new(.:format)
  3. 您应该在form_for中使用实例而不是符号:

    = form_for @transaction do |f|
    

    它会向/transactions发送POST请求。

答案 1 :(得分:1)

控制器中的new方法应更新如下:

class TransactionsController < ApplicationController
  def new
    @transaction = Transaction.new
  end

TransactionsController#create方法也需要更新。 Transaction#new方法正在传递三个参数,但它只应该将一个哈希作为参数。我不确定你的数据库中的字段是什么,但是这样的东西应该有效:

@transaction = Transaction.new({ email: current_user.email, money: 100.0 }.merge(params[:transaction]))

表格也应该更新:

= form_for :transaction do |f|
  = f.label :card_number, "Credit Card Number"
  = f.text_field :card_number