没有路由匹配我正在构建的Ruby应用程序中的[POST]

时间:2014-07-25 21:08:38

标签: ruby-on-rails ruby rest controller routing

我正在尝试构建一个允许用户使用restful routing创建旅行的应用程序,但是当用户登录并且他们尝试创建旅行时,我遇到了一个问题。 我得到“没有路线匹配[POST]”/ users / 8 / trips / new“”

这些是路线:

resources :users do 
  resources :trips
end

这是行程控制器:

class TripsController < ApplicationController
  def new
    @trip = Trip.new 
  end

  def create
    @trip = Trip.create(trip_params)
    redirect_to root_path
  end
end

这是创建新旅行的形式。这是我点击提交并收到错误的地方:

<div class="trip_form">
<%= form_for :trip do |f| %>  

    <%= f.label :where, "Where?" %><br/>
    <%= f.text_field :where, placeholder: "Hawaii" %><br>

    <%= f.label :when, "When?" %><br/>
    <%= f.text_field :when, placeholder: "#" %><br>


    <%= f.label :price_per_person, "Price per person? (Approximately)" %><br/>
    <%= f.text_field :price_per_person, placeholder: "$550" %><br>

    <%= f.submit "Create Trip Idea"%>
<% end %>

这些是路线:

$ rake routes
    Prefix Verb   URI Pattern                              Controller#Action
    user_trips GET    /users/:user_id/trips(.:format)          trips#index
               POST   /users/:user_id/trips(.:format)          trips#create
 new_user_trip GET    /users/:user_id/trips/new(.:format)      trips#new
edit_user_trip GET    /users/:user_id/trips/:id/edit(.:format) trips#edit
 user_trip GET    /users/:user_id/trips/:id(.:format)      trips#show
           PATCH  /users/:user_id/trips/:id(.:format)      trips#update
           PUT    /users/:user_id/trips/:id(.:format)      trips#update
           DELETE /users/:user_id/trips/:id(.:format)      trips#destroy
     users GET    /users(.:format)                         users#index
           POST   /users(.:format)                         users#create
  new_user GET    /users/new(.:format)                     users#new
 edit_user GET    /users/:id/edit(.:format)                users#edit
      user GET    /users/:id(.:format)                     users#show
           PATCH  /users/:id(.:format)                     users#update
           PUT    /users/:id(.:format)                     users#update
           DELETE /users/:id(.:format)                     users#destroy
      root GET    /                                        users#index

我以为我应该能够填写旅行新表格,当我按下提交时 自动与行程控制器中的create方法通信?当我做更改时:在表单中访问@trip我收到此错误:

Trips#new

中的NoMethodError

未定义的方法`trips_path'

谢谢!

2 个答案:

答案 0 :(得分:3)

form_for助手中存在一个小错误。它应该是:

<%= form_for @trip do |f| %>
  ...

帮助器将查看@trip对象并看到它是一个新对象(=尚未保存到数据库中),因此将选择POST /users/8/trips作为表单操作。

通过不将ActiveRecord对象交给帮助程序,生成的HTML表单没有动作,因此提交表单将POST到当前路径(这是新路径)

编辑

为了让帮助者为您拥有的嵌套资源情况选择路由,请使用:

<%= form_for [current_user, @trip] do |f| %>
  ...

假设current_user是您所指的用户对象。

答案 1 :(得分:3)

<%= form_for :trip do |f| %>  

应该是

<%= form_for [@user, @trip] do |f| %> 

因为您使用嵌套资源,所以您也需要这样做

# controller
def new
  @user = User.find(1)
  @trip = Trip.new
end

documentation for form_for

中的更多内容