Reputation: 179
I created a partial in post show#view which names _comments.html.erb
here it is
<p class="text-center">Poster un commentaire</p>
<%= simple_form_for [post, post.comments.new] do |f| %>
<%= f.error_notification %>
<%= f.input :content, label: "Commentaire"%>
<%= f.submit "Envoyer", class: "btn btn-primary" %>
<% end %>
and it render like that <%= render 'comments' %>
and above the partial (in post show#view) I do an iteration like that
<ul class="list-unstyled">
<% @post.comments.each do |comment| %>
<li>
<p><% comment.content %></p>
<% end %>
</li>
</ul>
But nothing appears when I create a new message, I don't userstand why.
I give your more code details
post.rb
has_many :comments, dependent: :destroy
comment.rb
belongs_to :user
belongs_to :post
The route is:
resources :posts do
resources :categories
resources :comments
end
Comments controller is
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
@comment.user_id = current_user.id
if @comment.save
flash[:success] = "You commented the hell out of that post!"
redirect_to :back
else
flash[:alert] = "There is a problem with your comment"
render root_path
end
end
def destroy
@comment = @post.comments.find(params[:id])
@comment.destroy
flash[:success] = "Comment deleted :("
redirect_to root_path
end
private
def set_post
@post = Post.find(params[:post_id])
end
def comment_params
params.require(:comment).permit(:content, :post_id, :user_id)
end
end
Thank you so much for your help.
Upvotes: 0
Views: 50
Reputation: 15954
You just missed the =
in the erb template on the <p>
line. Without it there won't be anything shown in the output. Also note that the </li>
and end
lines should be swapped so that these two blocks are not mixed together:
<ul class="list-unstyled">
<% @post.comments.each do |comment| %>
<li>
<p><%= comment.content %></p>
</li>
<% end %>
</ul>
By the way, there is another way to render collection partials like :
<ul class="list-unstyled">
<%= render :partial => "comment", :collection => @comments %>
</ul>
And there is no need to loop through the values in partial, it will manage this with the :collection
parameter, and then the comment partial should be like:
<li>
<p><%= comment.content %></p>
</li>
Upvotes: 3