KnowledgeMC KnowledgeMC - 3 months ago 16
Ruby Question

Correct Rails path to put in Embedded Ruby File for the view?

I'm building my first Rails app and I'm having trouble placing the correct path for a link in my embedded ruby file.

I want to link to a "Add new comment" page from a post. I want the user to be redirected for example to "http://localhost:3000/posts/1/comments/new" when they click the "Comment" link on the page. I think the nested routes are confusing me. Can someone help me out?

Here are my routes:

Prefix Verb URI Pattern Controller#Action
sessions_new GET /sessions/new(.:format) sessions#new
users_new GET /users/new(.:format) users#new
root GET / pages#home
help GET /help(.:format) pages#help
about GET /about(.:format) pages#about
contact GET /contact(.:format) pages#contact
signup GET /signup(.:format) users#new
login GET /login(.:format) sessions#new
POST /login(.:format) sessions#create
logout DELETE /logout(.:format) sessions#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
post_comments POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
post_comment DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy

Here's the code for the view from the .erb file (I placed a '#' where the path should be:

<div class="col-md-8">
<% if @user.posts.any? %>
<h3>Posts (<%= @user.posts.count %>)</h3>
<ol class="posts">
<% @user.posts.each do |post| %>
<li id="post-<%= %>">
<%= link_to gravatar_for(post.user, size: 50), post.user %>
<span class="user"><%= link_to, post.user %></span>
<span class="picture" style="color:red;"><%= post.picture %></span>
<span class="picture"><%= image_tag post.picture.url(:large) %></span>
<span class="content"><%= post.caption %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(post.created_at) %> ago.

<span class="edit_post">
<%= link_to "Edit", edit_post_path(@user, @post) %>
<span class="delete_post">
<%= link_to "Delete", post,
method: :delete, data:
{ confirm: "Are you sure you want to delete this post?"} %>

<span class="comment_post">
<%= link_to "Comment", '#' %>

<% end %>
<% end %>


This should map to your routing:

<%= link_to "Comment", new_post_comment_path(post_id: %>

and you can retrieve the post_id in your controller - params[:post_id]