1

我正在学习 Ruby on Rails,但遇到了一个问题:

ActiveRecord::RecordNotFound in BookmarksController#show 找不到带有 'id'= 的书签

控制器:

class BookmarksController < ApplicationController
    def index
       @bookmarks = Bookmark.all
    end
    def show
      @bookmark = Bookmark.find(params[:id])
    end

    def edit
    end

    def new
    end
end

看法:

<h2>Detail zum Favorit</h2>

<p>Titel: <%= h @bookmark.title %></p>

<p>URL: <%= h @bookmark.url %></p>

<p>Kommentar: <%= h @bookmark.comment %></p>

<p>Erstellt am: <%= @bookmark.created_at %></p>

<p>Geändert am: <%= @bookmark.updated_at %></p>

架构.rb:

create_table "bookmarks", force: :cascade do |t|
    t.string   "title"
    t.string   "url"
    t.text     "comment"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

路线.rb:

Rails.application.routes.draw do
  get 'bookmarks/index'
  get 'bookmarks/edit'
  get 'bookmarks/new'
  get 'bookmarks/show'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".
    resources :bookmarks

网址:

http://localhost:3000/bookmarks/show

我按照以下说明操作:http: //openbook.galileo-press.de/ruby_on_rails/ruby_on_rails_05_004.htm#mj035976f94f0c66066b0f06b2ffe8e16e

4

3 回答 3

0

index.html must look like

<h2>Detail zum Favorit</h2>

<% @bookmarks.each do |bookmark| %>

    <p>Titel: <%= h bookmark.title %></p>

    <p>URL: <%= h bookmark.url %></p>

    <p>Kommentar: <%= h bookmark.comment %></p>

    <p>Erstellt am: <%= bookmark.created_at %></p>

    <p>Geändert am: <%= bookmark.updated_at %></p>

    <%= link_to 'Show', bookmark_path(bookmark.id) %>

<% end %>

@bookmarks is a collection of objects hence loop through, to display the objects in the Array.

Have this in your routes.rb

Rails.application.routes.draw do
  resources :bookmarks
  ........
end

This automatically generates basic 7 restful URL's for Bookmark check by running rake routes

于 2015-01-11T14:37:18.887 回答
0

您不需要在 中指定 4 个get路径routes.rb,该resources方法添加了 7 个基本 REST 操作和 URL,如果您rake routes从终端调用,则可以看到它们。

正确的 URL 是/bookmarks/<id>基于这个 ID,记录将被加载到控制器中。

于 2015-01-11T14:26:47.913 回答
0

首先按照正确的教程学习rails,我会推荐使用这个[ http://guides.rubyonrails.org/getting_started.html][1]

第二件事是因为你定义的路线routes.rb

你不需要定义这些路线 -

get 'bookmarks/index'
get 'bookmarks/edit'
get 'bookmarks/new'
get 'bookmarks/show'

因为 rails 会自动生成 7 条基本路线。所以首先从你的routes.rb

这足以在您的路线文件中生成 7 条基本路线bookmarks。-

Rails.application.routes.draw do
  resources :bookmarks
  ........
end
于 2015-01-11T17:27:59.517 回答