Reputation: 3
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
<% @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.
Edit: Here is my routes.rb
Rails.application.routes.draw do
resources :posts
root "index#index"
end
Upvotes: 0
Views: 2271
Reputation: 449
I'm sorry for the wrong answer: <%= 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
? If so, just don't, visit /posts
and click the link. If it's link_to
method that generate the wrong url, please post the html that it generate.
Upvotes: 1
Reputation: 5633
To visit your index
route, you shouldn't be going to /posts/index
rather /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.
Run rake routes
to see the route mappings of your application
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
Upvotes: 2
Reputation: 18657
You called the Url wrong so it is taking '/posts/index'. Add a path to tell the action where to go, observe the 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
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)
Upvotes: 1