gpt4 book ai didi

ruby-on-rails - rails : no route matches form for url?

转载 作者:太空宇宙 更新时间:2023-11-03 16:42:58 27 4
gpt4 key购买 nike

我正在尝试制作一个表单,用户可以在其中使用回形针 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 %>

这是我的回放 Controller :

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 操作,但您需要将文件发送到创建 Controller 的 Action 。

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

编辑:

因为我可以看到你的路线。如果您使用 Scaffolding 创建路由,则您的 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

关于ruby-on-rails - rails : no route matches form for url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40951466/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com