I am trying to create a blog that has users, posts and comments. Each user can have many posts and many comments, so each post can have many comments. I have successfully created user sections and posts, but it's hard for me to create comments and then show them.
the 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 create and display comments in the message view, therefore ..
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 partial:
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 wrong here, but I'm new to rails, and I also tried form_for (@user, @post, @ post.comments.build), but that didn't work either. Anyways here is another partial:
opinions / 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>
Here again, I have problems referring to ... any suggestions would be great.