【问题标题】:ActiveRecord::RecordNotFound in PostsController#showActiveRecord::RecordNotFound in PostsController#show
【发布时间】:2014-03-20 06:10:00
【问题描述】:

当我访问http://127.0.0.1:3000/posts/show url 时出现上述错误,它给了我错误

Couldn't find Post with id=show
Extracted source (around line #5) 

def show
@post = Post.find(params[:id])--here is line number 5
end
def create
@post = Post.new(post_params)

activerecord (4.0.3) lib/active_record/relation/finder_methods.rb:198:in `raise_record_not_found_exception!'

访问网址http://127.0.0.1:3000/posts/index...时同样的问题

my controller file is

posts_controller.rb

class PostsController < ApplicationController
  def new
end
def show
  @post = Post.find(params[:id])
end
  def create
  @post = Post.new(post_params)

  @post.save
  redirect_to @post
  # or this command also works redirect_to action: :show, id: @post.id
end

def index
  @posts = Post.all
end
private
  def post_params
    params.require(:post).permit(:title, :text)
  end

end

my routes.rb file is
Blog::Application.routes.draw do
  resources :posts
  root to: "posts#index"
end

index.html.rb 文件是

<h1>Listing posts</h1>
 <h3><%= link_to 'New post', new_post_path %></h3>
<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
  </tr>

  <% @posts.each do |post| %>
    <tr>
      <td><%= post.title %></td>
      <td><%= post.text %></td>
    </tr>
  <% end %>
</table>
<h1>Hello,Rails</h1>
<%=link_to "My Blog",controller: "posts"%>

show.html.rb 文件是

这是用于从数据库中列出信息的显示文件,当直接从 url 访问时,此文件会出现问题 这是用于从数据库中列出信息的显示文件,当从 url 直接访问时,此文件会出现问题 这是用于列出信息的显示文件从数据库,直接从 url 访问时,此文件出现问题 这是从数据库中列出信息的显示文件,从 url 直接访问时,此文件出现问题 这是从数据库中列出信息的显示文件,此文件在访问时出现问题直接来自网址

<p>
  <strong>Title:</strong>
  <%= @post.title  %>
</p>

<p>
  <strong>Text:</strong>
  <%= @post.text %>
</p>
<%= link_to 'Back', posts_path %>

这是从数据库中列出信息的显示文件,当直接从 url 访问时,此文件会出现问题 这是从数据库中列出信息的显示文件,当直接从 url 访问时,此文件会出现问题

【问题讨论】:

    标签: ruby-on-rails-4


    【解决方案1】:

    您需要提供一个 ID。未找到记录,因为您提供“show”作为 id。 http://ruby.railstutorial.org/chapters/sign-up#code-user_show_action

    示例:访问 posts/1 而不是 posts/show

    【讨论】:

    • 对于索引只需 /posts。或者只是根,因为它在 routes.rb 中定义为根。
    • 如果我想使用posts/show而不是posts/1,我怎样才能得到结果?
    • 你想通过帖子/节目看到什么?您可以映射路线/显示去任何你想去的地方。正如@rails4guides.com 所说,如果您想显示所有帖子,只需访问“localhost:3000/posts”即可查看索引。基本路由信息脱轨教程:ruby.railstutorial.org/chapters/… 更深入的路由信息​​:guides.rubyonrails.org/routing.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多