我应该做的帮手? 或者这是否慢?(Am I supposed to do this in hel

2019-11-01 11:50发布

在这种情况下,该模式会更快?
显然样式1与助手看起来更精致,看上去干净。
但它发送SQL每当USER_LINK方法被调用的时间。
这可以调出在一个页面加载到100次。

哪种方式对基准性能更好?

样式1。 有了帮手

application_helper

def user_link(username)
    link_to User.find_by_username(username).user_profile.nickname, show_user_path(username)
end

视图

<% @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 %>

模式2。 没有帮手。 仅仅只有视图

<% @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 %>

Answer 1:

尝试

# Topics model
#via scope
scope :get_topic_list, lambda do
  order("updated_at DESC").joins(:comment_threads => :user).limit(100)
end

#via method
def self.get_topic_list
  Topic.order("updated_at DESC").joins(:comment_threads => :user).limit(100)
end

# in your controller or move to model itself (recommened)
@topics = Topic.get_topic_list

# in you view
<% @topics.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 %>


文章来源: Am I supposed to do this in helper? or does this make slower?