Rails:没有路由匹配 url 的形式?

Rails: no route matches form for url?

我正在尝试制作一个表单,用户可以在其中使用回形针 gem 上传文件。这是我到目前为止得到的:

在 new.html.erb:

<%= form_for @replay, url: replay_path(@replay), :html => { :multipart => true } do |form| %>
    <%= form.file_field :r_file %>

    <%= form.submit "Submit" %>
<% end %>

这是我的回放控制器:

class ReplayController < ApplicationController
    def index
    end

    def new
        @replay = Replay.new
    end

    def create
        @replay = Replay.create(params[:replay])
        if @replay.save
            redirect_to @replay
        else
            render 'new'
        end
    end

    def show
        @replay = Replay.find(params[:id])
        #puts @replay.attachment.file_name
    end

    def update
    end

    private

    def replay_params
        params.require(:replay).permit(:r_file, :map)
    end
end

我的路线:

  home_index GET    /home/index(.:format)      home#index
replay_index GET    /replay(.:format)          replay#index
             POST   /replay(.:format)          replay#create
  new_replay GET    /replay/new(.:format)      replay#new
 edit_replay GET    /replay/:id/edit(.:format) replay#edit
      replay GET    /replay/:id(.:format)      replay#show
             PATCH  /replay/:id(.:format)      replay#update
             PUT    /replay/:id(.:format)      replay#update
             DELETE /replay/:id(.:format)      replay#destroy
        root GET    /                          home#index

但我在 new.html.erb 的表单中收到以下错误:

No route matches {:action=>"show", :controller=>"replay", :id=>nil} missing required keys: [:id]

我不知道为什么 :id 是 nil?有什么想法吗?

添加 url: replays_path 而不是 url: replay_path(@replay) 当前 form_for 指的是 show 操作,但您需要将文件发送到控制器的 create 操作。

<%= form_for @replay, url: replays_path, :html => { :multipart => true } do |form| %>

编辑:

因为我可以看到你的路线。如果您使用脚手架创建了路线,则您的 index 操作通常由 replay_index 引用 replays。所以在这种情况下你需要添加 url: replay_index_path.

<%= form_for @replay, url: replay_index_path, :html => { :multipart => true } do |form| %>

Note: if you correct your routes, there is no need to mention url option in form_for tag. it will automatically refer to create action when you submit form. it is recommended to correct your route.

更新您的 routes.rb。使用 resource

创建路线
resources :replays

它在您的应用程序中创建七个不同的路由,所有路由都映射到 ReplayController。每个操作都映射到数据库中的特定 CRUD 操作。

你的路线应该是这样的

    replays GET    /replay(.:format)          replay#index
            POST   /replay(.:format)          replay#create
 new_replay GET    /replay/new(.:format)      replay#new
edit_replay GET    /replay/:id/edit(.:format) replay#edit
     replay GET    /replay/:id(.:format)      replay#show
            PATCH  /replay/:id(.:format)      replay#update
            PUT    /replay/:id(.:format)      replay#update
            DELETE /replay/:id(.:format)      replay#destroy