I got two models: Post and Comment. Comment is a nested resource of Post:
routes.rb:
resources :posts do
resources :comments
end
I’m enabling users to edit the comments that are displayed in the post show view:
posts/show.hmtl.erb:
<%= render @comments %>
comments/_comment.html.erb:
<%= link_to "Edit Post Comment", edit_post_comment_path(@post, comment) %>
This form:
comments/_form.html.erb:
<h4>Add a comment:</h4>
<%= form_for([@post, @post.comments.build]) do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<% unless current_user == nil %>
<% if current_user.id == @post.user_id %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<% end %>
<% end %>
<%= link_to 'Back', posts_path %>
Is for creating a comment in the show view.
I need another form to edit the comment in a new template:
comments/edit.html.erb:
<h1>Edit comment</h1>
<%= render 'form2' %>
<%= link_to 'Back', posts_path %>
comments/form2.html.erb:
<h4>Edit comment:</h4>
<%= form_for() do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Back', posts_path %>
Not sure what to place here:
<%= form_for(HERE) do |f| %>
Any suggestions?
EDIT
comments_controller.rb:
class CommentsController < ApplicationController
def show
@comment = Comment.find(params[:id])
end
def new
@comment = Comment.new
end
def edit
@comment = Comment.find(params[:id])
end
def update
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
@comment.update_attributes(params[:comment])
redirect_to @post
end
def create
@post = Post.find(params[:post_id])
comment_attr = params[:comment].merge :user_id => current_user.id
@comment = @post.comments.create(comment_attr)
redirect_to post_path(@post)
end
end
Comments are nested resources and that means a comment is always tied to a particular Post. In the edit action you’ll get both comment_id and post_id as parameters. You should load both comment and post by those id’s. Don’t build the comment in the form to reuse the form for both new and edit actions. Change your form to:
comments/_form.html.erb
comments_controller.rb
and in the posts_controller.rb