How can I fetch records just like below with using Model and controler not view?
Pattern1. With helper
application_helper
def user_link(username)
link_to User.find_by_username(username).user_profile.nickname, show_user_path(username)
end
view
<% @topics.order("updated_at DESC").limit(100).each do |topic| %>
<%= user_link(topic.comment_threads.order("id").last.user.username) if topic.comment_threads.present? %>
<% end %>
Pattern2. Without helper. Just only view
<% @topics.order("updated_at DESC").limit(100).each do |topic| %>
<%= link_to(topic.comment_threads.order("id").last.user.nickname, show_user_path(topic.comment_threads.order("id").last.user.username) ) if topic.comment_threads.present? %>
<% end %>
UPDATE
<% @community.topics.eager.recent.each do |topic| %>
<%= user_link(topic.comment_threads.order("id").last.user.username) if topic.comment_threads.present? %>
<% end %>
SQL code or SQL builders should never ever reach the view layer. This should be in your models. I wouldn’t even place queries like this in the controller.
I’d extract the
topicSQL builder into a named scope. On top of that, to avoid n+1 queries, I’d create another named scopeeager:Then I’d move the
comment_threadsSQL builder into your comment_threads model:We can now tidy up your views:
Allow me to sell Slim to you (erb alternative):
I might have even gone a step further and extracted the
user_linkinto aUserDecorator. See https://github.com/drapergem/draper for details.Summary
topicintoeagerandrecentscopes undertopiccomment_threadsintolast_user_nicknameundercomment_threaduser_linkinto aUserDecorator