I'm developing a litte blog like application and at the moment I'm facing a problem that I can't resolve.
I have 2 models at the moment :
1. Post
2. Comment
I can already manage my posts without difficulties but I have some problems with comments. I chose to make a relation has_many / belongs_to between my post and my comment models. I'd like to display all the comments related to a post when the user is on the post's page. My erb looks like this :
#some code
#...
#...
#render the comments
<%= render :template => "comments/index", :locals => {:post_id => @post.id} %>
My problem here is that the method index from my CommentsController is never called. I put some puts in the index method and they are never displayed in the console.
Should I use another tag to render the view ? Is there another way to do this ?
Thanks in advance for your help.
If the post view is the only page to show comments, you don't have to call comments/index
to get comments, just show comments when rendering the post view, for example
In your post view
#some code
#...
# render comments
<% @post.comments.each do |c| %>
<%= c.content%>
# ...
<% end %>
Or put them in a partial with a post
parameter if comments are used in many views
In app/views/partials/_comments.html.erb
# render comments
<% post.comments.each do |c| %>
<%= c.content%>
# ...
<% end %>
and render this partial where you want to show comments:
#some code
#...
# render comments
<%= render partial: "partials/comments", locals: { post: @post } %>
Using comments/index
to get comments and showing them in a view is more likely the frondend tech such as Javascript/AJAX to load page parts dynamically. In this case, the comments/index
is more likely an API call(render a JSON format instead of a html view).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.