"schools"} 缺少必需的键:[:id]-6ren"> "schools"} 缺少必需的键:[:id]-我不知道为什么我无法为项目中的每所学校创建信息链接。这是完整的错误: No route matches {:action=>"show", :controller=>"schools"} missin-6ren">
gpt4 book ai didi

ruby-on-rails - 没有路由匹配 { :action= >"show", :controller= >"schools"} 缺少必需的键:[:id]

转载 作者:行者123 更新时间:2023-12-02 19:24:07 25 4
gpt4 key购买 nike

我不知道为什么我无法为项目中的每所学校创建信息链接。这是完整的错误:

No route matches {:action=>"show", :controller=>"schools"} missing required keys: [:id] <%= link_to "Info", school_path, class: "btn btn-info" %>

这是我的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

最佳答案

因为您正在学习,所以我会给您一些背景信息。

--

No route matches

该错误意味着您的 Rails routes找不到您引用的路线。

它给出了以下规范:

missing required keys: [: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 指令创建的路由。我现在不会解释它 - 只是说当您调用 school_path 时,您指的是 route 的 GET/schools/:id 路径。

因此,您必须记住的是,当您调用此路由时,您必须向其发送一个id - url.com/schools/1 。这允许 Controller 查找适当的记录 (School.find params[:id])。

当你打电话时...

<%= link_to "Info", school_path, class: "btn btn-info" %>

...您没有将任何参数传递给 school_path

要修复它,您必须传递id,如果您传递适当的对象,Rails 会自动执行此操作:

<%= link_to "Info", school_path(school), class: ".." %>

<%= link_to "Info", school, class: "..." %>

关于ruby-on-rails - 没有路由匹配 { :action= >"show", :controller= >"schools"} 缺少必需的键:[:id],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718874/

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