So I have a forum application and double nested resources. Section-->Topic-->Replies and are set up as such in the application controller (Rails 3 style). I'm looking at the section view and am trying to sort my topics. In most forums the most logical sorting method is by when it's updated last. This would be simple if it was just by replies. The obvious problem is, there are topics without replies, so sorting simply by replies won't work.
<% @section.topics.sort_by{ ?? }.each do |topic| %>
<tr>
<td class="topic"><%= link_to topic.subject, [@section, topic] %></td>
<td class="postCount"><%= topic.replies.count %></td>
<td class="date">
<% if topic.replies.empty? %>
<%= topic.created_at.strftime("%I:%M%p %m/%d/%y") %>
<% else %>
<%= topic.replies.last.created_at.strftime("%I:%M%p %m/%d/%y") %>
<% end %>
</td>
</tr>
<% end %>
So basically开发者_C百科 if the replies are empty, you pull when the topic was created. If there are replies, pull when the last one was created. This displays wonderfully in the show sections view, but I have no clue how to sort using this.
I tried making a method in the topic model called "last_updated". I wrote it like:
def last_update(sectionTopic)
if sectionTopic.replies.empty?
return sectionTopic.created_at
else
return sectionTopic.replies.last.created_at
end
end
And passed it in through the view:
<% @section.topics.sort_by{ |topic| topic.last_update(@section.topics)}.each do |topic| %>
But I get a undefined method `replies' when I do this. Any ideas? Thank you.
From what I can tell,
topic.last_update(@section.topics)
should be:
topic.last_update(topic)
精彩评论