【发布时间】:2014-07-27 02:00:57
【问题描述】:
我正在开发 Rails 应用程序,但遇到以下错误消息。
ActiveRecord::RecordNotFound in RecipesController#show
Couldn't find recipe with id=index
Extracted source (around line #8)
def show
@recipe = Recipe.find(params[:id]) # This line is highlighted in pink
end
我相信这与我的路线有关。我的索引页面的 url 是 localhost:3000/games/index (我在我的食谱控制器上调用 index 操作。我通过资源创建了该操作:recipe 创建了包括索引在内的七个宁静路线。)但是,当我访问它时, ROR 认为我正在通过 show route 访问 id 为 index 的游戏。事实上,我想将我的索引页面设置为 localhost:3000/recipes。我不想要最后的索引。
这是我的食谱控制器
class RecipesController < ApplicationController
def index
@recipe = Recipe.all
end
def show
@recipe = recipe.find(params[:id])
end
def new
@recipe = Recipe.new
end
def create
@recipe = Recipe.new(params[:id])
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
def edit
end
def update
end
def destroy
end
end
如你所见,我定义了 7 条常见的 RESTful 路由,并完成了其中的 4 条。
这是我的 routes.rb 文件
Recipes::Application.routes.draw do
resources :recipes
end
通过声明资源 :recipes,我创建了 7 条路由,而无需在多行中声明它们。
这是 rake 路由的结果
Prefix Verb URI Pattern Controller#Action
recipes GET /recipes(.:format) recipes#index
POST /recipes(.:format) recipes#create
new_recipe GET /recipes/new(.:format) recipes#new
edit_recipe GET /recipes/:id/edit(.:format) recipes#edit
recipe GET /recipes/:id(.:format) recipes#show
PATCH /recipes/:id(.:format) recipes#update
PUT /recipes/:id(.:format) recipes#update
DELETE /recipes/:id(.:format) recipes#destroy
这是我的 index.html.erb 文件,位于 apps/views/recipes 目录中
<h1>Here is a list of recipes</h1>
<table>
<thead>
<tr>
<th>Recipe</th>
<th>Cook Time</th>
<th>Prep Time</th>
<th>Difficulty</th>
</tr>
</thead>
<tbody>
<% @recipes.each do |recipe| %>
<tr>
<td><%= recipe.recipe %></td>
<td><%= recipe.cooktime %></td>
<td><%= recipe.preptime %></td>
<td><%= recipe.difficulty %></td>
</tr>
<% end %>
</tbody>
</table>
这是我的迁移文件
class CreateRecipes < ActiveRecord::Migration
def change
create_table :recipes do |t|
t.string :recipe
t.string :cooktime
t.string :preptime
t.integer :difficulty
t.timestamps
end
end
end
这是我的 application.html.erb 文件,用作每个网页的模板
<!DOCTYPE html>
<html>
<head>
<title>Recipes</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
<%= link_to "Home", recipes_path %>
<%= link_to "Edit", edit_recipe_path(:id) %>
<%= link_to "New", new_recupe_path %>
<%= link_to "Delete" %>
</body>
</html>
我尝试通过 rails 控制台创建 ActiveRecord 对象并保存它们。所以 ActiveRecord 对象确实存在 ID。我不知道我哪里出错了。
如果您需要更多信息,请告诉我。
感谢您的帮助。感谢您的宝贵时间。
【问题讨论】:
-
不知道。但请尝试发布“rake routes”的结果以帮助了解发生了什么。
-
感谢您的建议。我用我所有的路线更新了 OP。所有这些都是从资源中声明的:游戏
标签: ruby-on-rails activerecord routing params