I'm trying to make a blog which has users, posts and comments. Each user can have many posts and many comments similarly each post can have many comments. I have successfully made the user and post sections but am having difficulty creating comments and then displaying them.
code:
routes.rb :
resources :users do
resources :posts do
resources :comments
end
end
user.rb :
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
post.rb :
belongs_to :user
has_many :comments, dependent: :destroy
comment.rb :
belongs_to :post, :user
I'm creating and displaying comments in the post's view itself so..
posts_controller.rb :
def show
@user = current_user
@post = Post.find(params[:id])
end
view/posts/show.html.erb :
<p><strong>Title:</strong><%= @post.title %></p>
<p><strong>Text:</strong><%= @post.text %></p>
<% if @user.posts.comments.empty? %>
<h2>Comments</h2>
<%= render @posts.comments %>
<% end %>
<h2>Add a comment:</h2>
<%= render "comments/form" %>
<%= link_to 'Edit Post', edit_user_post_path(@user.id,@post) %> |
<%= link_to 'Back to Posts', user_posts_path(@user.id) %>
comments_controller.rb :
class CommentsController < ApplicationController
def create
@user = current_user
@post = @user.posts.find(params[:post_id])
@comment = @user.posts.comments.create(params[:comment])
redirect_to user_post_path(@user.id,@post)
end
def destroy
@user = current_user
@post = @user.posts.find(params[:post_id])
@comment = @user.posts.comments.find(params[:id])
@comment.destroy
redirect_to user_post_path(@user.id,@post)
end
end
And the partials are:
views/comments/_form.html.erb :
<%= form_for([@user,@post,@comment]) do |f| %>
<p>
<%= @user.email %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
I think my form_for is not right here but I'm new to rails and I've also tried form_for(@user,@post,@post.comments.build) but that didn't work either.. Anyways here's another partial:
views/comments/_comment.html.erb:
<p><strong>Commenter:</strong><%= @user.email %></p>
<p><strong>Comment:</strong><%= comment.body %></p>
<p><%= link_to 'Destroy Comment', [comment.post, comment],method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
Again here I'm having trouble with link to...any suggestions would be great.