本文介绍了我应该在助手中做到这一点吗?或者这会使速度变慢吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这种情况下,哪种模式会更快?
显然,带有帮助程序的 Pattern1 看起来更复杂,看起来更干净.
但是每次调用 user_link 方法时它都会发送 SQL.
在这里,它在一页加载时最多调用 100 次.
In this case which pattern will be faster?
Obviously Pattern1 with helper looks much more sophisticated and looks clean.
But it send SQL every time when user_link method is called.
Here it calls up to 100times at one page loading.
哪种方式对基准性能更好?
Which way would be better for benchmark performance?
模式 1.有帮手
application_helper
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 %>
推荐答案
try
# 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 %>
这篇关于我应该在助手中做到这一点吗?或者这会使速度变慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!