我检查了所有已经提出相同问题的主题,但没有得到答案当我试图创建一个新的赛车,使用新的赛车路径,我得到以下错误。
ActionController::UrlGenerationError in Racers#new
Showing /home/dsmegha/RoR-Coursera/Mongo/raceday/app/views/racers/_form.html.erb where line #1 raised:
No route matches {:action=>"show", :controller=>"racers", :id=>""} missing required keys: [:id]
Extracted source (around line #1):
1 <%= form_for(@racer) do |f| %>
2 <% if @racer.errors.any? %>
3 <div id="error_explanation">
4 <h2><%= pluralize(@racer.errors.count, "error") %> prohibited this racer from being saved:</h2>
5
6 <ul>
我的rake路由输出:
$ rake routes
Prefix Verb URI Pattern Controller#Action
racers GET /racers(.:format) racers#index
POST /racers(.:format) racers#create
new_racer GET /racers/new(.:format) racers#new
edit_racer GET /racers/:id/edit(.:format) racers#edit
racer GET /racers/:id(.:format) racers#show
PATCH /racers/:id(.:format) racers#update
PUT /racers/:id(.:format) racers#update
DELETE /racers/:id(.:format) racers#destroy
root GET / racers#index
我的控制器:
def show
end
def new
@racer = Racer.new
end
def create
@racer = Racer.new(racer_params)
respond_to do |format|
if @racer.save
format.html { redirect_to @racer, notice: 'Racer was successfully created.' }
format.json { render :show, status: :created, location: @racer }
else
format.html { render :new }
format.json { render json: @racer.errors, status: :unprocessable_entity }
end
end
end
def racer_params
params.require(:racer).permit(:number, :first_name, :last_name, :gender, :group, :secs)
end
我的新.html.erb:
<h1>New Racer</h1>
<%= render 'form' %>
<%= link_to 'Back', racers_path %>
抛出错误的表单.html.erb的起始部分。
<%= form_for(@racer) do |f| %>
<% if @racer.errors.any? %>
index.html.erb的一部分,从中可以创建新的赛车手。
<%= link_to 'New Racer', new_racer_path %>
我的理解是,当单击新用户时,将执行控制器中的新操作,创建一个新的Racer并将其分配给@Racer,然后呈现new.html.erb,进而呈现_表单我是一个rails新手,如果你能帮我调试它,那就太好了。
最佳答案
我相信你的赛车模型可能设置错误。
定义如下:
# app/models/racer.rb
class Racer < ActiveRecord::Base
end
如果您的racer类不是从activerecord::base继承的,那么它不会响应
new_record?
方法,因此form_for不会正确地选择路由。