【问题标题】:How to fix rails Couldn't find Post without an ID Error如何修复rails找不到没有ID错误的帖子
【发布时间】:2013-11-10 07:46:24
【问题描述】:

我是 Rails 新手,对 ruby​​ 知之甚少,我刚刚看过 Rails Guide 4.0 的教程。一切都很顺利,只是卡在一个错误上:找不到没有 ID 的帖子。

我按照 Rails Guide Getting Started Of Rails 中的所有操作。

这是来自 rails 指南的代码:

def show
  @posts = Post.find(params[:id])
end

这是查看代码:

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

<p>
  <strong>Text:</strong>
  <%= @posts.text %>
</p>

在此代码导轨指南告诉您最终应该能够创建新帖子之后。访问 localhost:3000/posts/new 并试一试!但是在创建新帖子后它向我显示错误。

我认为这可能是问题,因为我还没有创建索引操作,所以我完成了索引,在索引操作之后,当我尝试正常访问此地址时,它应该显示数据库中的所有记录,而不是显示显示相同错误的记录: 找不到没有 ID 的帖子

我在 stackoverflow 上尝试了太多帖子,但都与其他一些对我无用的操作有关。

请帮我解决这个问题,我只是认为这不应该是因为我正在遵循 Rails 指南。

我正在关注 Rails 入门指南,因为它说我添加了索引操作和显示操作。因此,正如书中所说,当您访问此地址 /posts 时,您应该看到所有帖子,并且当您创建新帖子时,它会重定向以显示您输入的最后一个帖子,

我使用的是redirect_to @post,但随之而来的错误我卡住了,然后我使用redirect_to action: :show, id: @post.id

当我创建一个新帖子时它正在工作,然后它重定向到 /posts?id=last_inserted_id 但是我看到其他脚手架地址应该是 posts/1 等,当我访问 /posts 它应该显示所有定义为的帖子操作控制器中的索引。

routes.rb

<code>
  Blog::Application.routes.draw do
  root "welcome#new"

  resource :posts
</code>

控制器:

class PostsController < ApplicationController


  def index
    @post = Post.all
    respond_to do |format|
      format.html #index.html.erb
    end
  end

  def show
    @post = Post.find(params[:id])
    respond_to do |format|
      format.html #show.html.erb
    end
  end

  def new

  end

  def create
    @post = Post.new post_params
    @post.save
    redirect_to action: :show, id: @post.id
  end

  private
    def post_params
      params.require(:post).permit(:title, :message)
    end
end

谢谢

【问题讨论】:

  • 1.展示您如何构建链接以显示操作(从视图中插入您的代码)。 2. 如果你为帖子定义的路由不是resources :posts,你也应该显示你的路由。
  • 1:我正在向地址栏添加操作,如下所示:/posts/etc 2:我正在使用资源:posts
  • 喜欢/posts/1 ?你在日志服务器(或development.log)中看到了什么?
  • 写入 /posts/1 时出现此错误 --- 没有路由匹配 [GET] "/posts/1"
  • smth 路由有问题。当您收到错误Couldn't find Post without an ID 时,您在地址栏中究竟写了什么?发布你的routes.rb - 因为resources :posts 应该为127.0.0.1:3000/posts/1 添加路由,你会得到错误Post with id=1 not found 但不是No route matches...

标签: ruby-on-rails-4


【解决方案1】:

你应该使用resources :posts 而不是resource

resources 生成“完整”CRUD - 7 个操作 http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources

resource生成路由uniq资源(无动作​​showhttp://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resource

【讨论】:

  • 感谢您解决了我的问题,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
相关资源
最近更新 更多