Reputation: 1692
I haven't found a single result related to my question when googleing, but it appears to me to be a fairly simple question:
Given is an article model and a comment model. Now, on the article show page, when listing all the article's comments, each comment should have its chronological id within that article, not its overall id.
The associations and everything work fine but I have no idea how to implement the 'relative' comment_id without going the rather complicated way and manually adding an article_comment_id column to my comment model and dealing with that attribute in my controller.
Is there no easy method to call an objects id within its parent model that it belongs_to?
Upvotes: 0
Views: 127
Reputation: 2438
As far as I know, there is not an automatic way to ask a record where it is indexed with its peers.
The way I've done this is just to keep track of the index while iterating through the array.
So for ERB:
<% @article.comments.each_with_index do |comment, index| %>
<div class="comment_id"><%= index + 1 %></div>
<div class="content"><%= comment.content %></div>
Or HAML:
[email protected]_with_index do |comment, index|
.comment_id= index + 1
.content= comment.content
If your paginating, you'll need to have index + 1 + (page*num_items)
or something.
You could save an index in the database, by adding a column such as iteration_id
and then add an before-create filter to the Comment model like this:
before_create do
last_comment = article.comments.unscoped.order("iteration_id DESC").select('iteration_id').first
self.iteration_id = last_comment ? last_comment.iteration_id + 1 : 0
true
end
You'd need to do something when comments are destroyed as well.
Hope that helps!
Upvotes: 1
Reputation: 107728
You can iterate through them using a partial:
<%= render @article.comments %>
Inside the partial, you can reference the count of the comments with comment_count
. This is an automatic feature that is provided by Rails.
Upvotes: 1