我不知道为什么我无法为项目中的每所学校创建信息链接。这是完整的错误:
没有路线匹配{:action =>" show",:controller =>"学校"}失踪 必需的键:[:id]<%= link_to" Info",school_path,class:" btn BTN-信息" %GT;
这是我的index.html.erb:
<% @schools.each do |school| %>
<%= school.name %>
<%= link_to "Info", school_path, class: "btn btn-info" %>
<br>
<% end %>
schools_controller.rb:
class SchoolsController < ApplicationController
def show
@school = School.find(params[:id])
end
def new
@school = School.new
end
def edit
@school = School.find(params[:id])
end
def index
@schools = School.all
end
def create
@school = School.new(school_params)
@school.save
redirect_to @school
end
private
def school_params
params.require(:school).permit(:name)
end
end
答案 0 :(得分:3)
因为你正在学习,我会给你一些背景信息。
-
没有路线匹配
错误表示您的Rails routes无法找到您所引用的路线。
它给出了以下规范:
缺少必需的密钥:[:id]
这意味着路径存在,但您尚未填写id
参数。
-
为了帮助您了解其工作原理,请考虑following:
GET /photos photos#index display a list of all photos
GET /photos/new photos#new return an HTML form for creating a new photo
POST /photos photos#create create a new photo
>> GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit photos#edit return an HTML form for editing a photo
PATCH/PUT /photos/:id photos#update update a specific photo
DELETE /photos/:id photos#destroy delete a specific photo
这些是在Rails中使用resources
指令创建的 routes 。我现在不会解释它 - 只是说当你拨打school_path
时,你指的是路线中的GET /schools/:id
路径。
因此,您必须记住的是,当您调用此路线时,您必须向其发送id
- url.com/schools/1
。这允许控制器查找适当的记录(School.find params[:id]
)。
当你打电话......
<%= link_to "Info", school_path, class: "btn btn-info" %>
...你没有将任何参数传递给school_path
。
要修复它,你必须传递id
,如果传递适当的对象,Rails会自动执行:{/ p>
<%= link_to "Info", school_path(school), class: ".." %>
或
<%= link_to "Info", school, class: "..." %>
答案 1 :(得分:2)
您需要将学校对象或学校ID传递给school_path方法。所以它可以通过该id创建路径。你可以这样做;
<% @schools.each do |school| %>
<%= school.name %>
<%= link_to "Info", school_path(school), class: "btn btn-info" %>
<br>
<% end %>