[英]Rails: Couldn't find Post with 'id'=index
So in my post controller, I have 所以在我的后控制器中,
def index
@post = Post.all.order('created_at DESC')
end
def show
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :body)
end
and in my .erb file 在我的.erb文件中
<% @post.each do |post| %>
<h2 class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y")</p>
<% end %>
The link is supposed to be picking up the 6 in /posts/6, but I suppose it isnt. 该链接应该在/ posts / 6中获得6,但我认为它不是。
Edit: Here is my routes.rb 编辑:这是我的routes.rb
Rails.application.routes.draw do
resources :posts
root "index#index"
end
To visit your index
route, you shouldn't be going to /posts/index
rather /posts
. 要访问
index
路线,您不应该去/posts/index
而是/posts
。
The error is likely occurring because 该错误很可能是由于
GET /posts/index
would map to /posts/:id
, which would be calling the show action of your posts_controller. GET
/posts/index
将映射到/posts/:id
,这将调用posts_controller的show操作。
Run rake routes
to see the route mappings of your application 运行
rake routes
以查看应用程序的路由映射
Sidenote: I don't think your variable nomenclature is the best. 旁注:我认为您的可变术语不是最好的。 If you have a collection of objects, I think it makes sense to call them
@posts
, to avoid confusions, while a single instance could be called @post
如果您有一组对象,我认为将它们称为
@posts
以避免混淆,而将单个实例称为@post
是@post
I'm sorry for the wrong answer: <%= link_to post.title, post_path(post) %>
. 对于错误的答案,我们感到抱歉:
<%= link_to post.title, post_path(post) %>
。
I check, and it work. 我检查,它正常工作。 This usage is not the problem.
这种用法不是问题。 I doubt that if you keep visit
/posts/index
? 我怀疑您是否继续访问
/posts/index
? If so, just don't, visit /posts
and click the link. 如果是这样,请不要访问
/posts
并单击链接。 If it's link_to
method that generate the wrong url, please post the html that it generate. 如果是
link_to
方法生成错误的URL,请发布它生成的HTML。
You called the Url wrong so it is taking '/posts/index'. 您将网址称为错误,因此采用了“ / posts / index”。 Add a path to tell the action where to go, observe the post_path(post)
添加一条路径来告诉操作要去哪里, 观察post_path(post)
<% @post.each do |post| %>
<h2 class="post_wrapper">
<h2 class="title"><%= link_to post.title, post_path(post) %></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y")</p>
<% end %>
Check these routes for more info, You can send an oject in place of id too, so post_path(post)
sends you to post detail page 检查这些路线以获取更多信息,您也可以发送oject代替id,因此
post_path(post)
会将您发送到发布详细信息页面
HTTPVerb Path Controller#Action Named Helper
GET /posts posts#index posts_path
GET /posts/new posts#new new_post_path
POST /posts posts#create posts_path
GET /posts/:id posts#show post_path(:id)
GET /posts/:id/edit posts#edit edit_post_path(:id)
PATCH/PUT /posts/:id posts#update post_path(:id)
DELETE /posts/:id posts#destroy post_path(:id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.