Topic: Cannot get Post and Comments app working

I have created a simple Rails App based on various tutorials. The simple version works. However when I attempt to tweak it to add more functionality it breaks.

The below is an extract of the posts view and comments controller. How do I simply add a link against each comment to edit, delete, show. Whenever I add links it leads to routing issues.

routes.rb

     resources :posts do
       resources :comments
     end

posts/show.html.erb

<p id="notice"><%= notice %></p>

<h2>Post</h2>

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

<p>
  <b>Body:</b>
  <%= @post.body %>
</p>


<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %> |
<%= link_to 'Comments', post_comments_path(@post) %>

<h2>Add a comment</h2>

<%= form_for([@post, @post.comments.build]) do |f| %>
    <div class="field">
      <%= f.label :name %><br />
      <%= f.text_field :name %>
    </div>
    <div class="field">
      <%= f.label :body %><br />
      <%= f.text_area :body %>
    </div>
    <div class="actions">
      <%= f.submit %>
    </div>

 <% end %>

<h2>Comments</h2>

<%# @post.comments = prints all comments%>
<% @post.comments.each do |c| %>
    <p>
      <b><%=h c.name %> said:</b><br />
      <%= c.created_at %>
    </p>

    <p>
      <%=h c.body %>
    </p>

    <p>
      <%=h c.id %>
    </p>

 
<% end %>


comments_controller.rb:

  def edit
    #1st you retrieve the post thanks to params[:post_id]
    @post = Post.find(params[:id])
    #2nd you retrieve the comment thanks to params[:id]
    @comment = post.comments.find(params[:post_id])
  
  end

Last edited by dmuk (2012-09-18 16:30:10)

Re: Cannot get Post and Comments app working

<% @post.comments.each do |c| %>
    <p>
      <b><%=h c.name %> said:</b><br />
      <%= c.created_at %>
    </p>

    <p>
      <%=h c.body %>
    </p>

    <p>
      <%=h c.id %>
    </p>


<% end %>

Just add the links before th end statement in your comments loop

Something like this?

<% @post.comments.each do |c| %>
    <p>
      <b><%=h c.name %> said:</b><br />
      <%= c.created_at %>
    </p>

    <p>
      <%=h c.body %>
    </p>

    <p>
      <%=h c.id %>
    </p>

<%= link_to 'Edit', edit_post_comment_path([@post, c]) %> |
<%= link_to 'Show', post_comment_path([@post, c]) %>
 
<% end %>

The links above reflect the routes you have set up but whether or not it will work all depends on how you set up your controllers and the actions within the controllers and what views you have associated with them.
It's really impossible to answser any more clearly without further information

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)