Ruby on rails 我是不是应该在家里做这件事?或者这会使速度变慢?

Ruby on rails 我是不是应该在家里做这件事?或者这会使速度变慢?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,在这种情况下,哪种模式更快? 显然,带有辅助对象的Pattern1看起来更复杂、更干净。 但每次调用用户链接方法时,它都会发送SQL。 在这里,一次页面加载最多调用100次 哪种方式对基准性能更有利 模式1。与助手一起 应用程序辅助程序 def user_link(username) link_to User.find_by_username(username).user_profile.nickname, show_user_path(username) end 看法 模式2。没

在这种情况下,哪种模式更快?
显然,带有辅助对象的Pattern1看起来更复杂、更干净。
但每次调用用户链接方法时,它都会发送SQL。
在这里,一次页面加载最多调用100次

哪种方式对基准性能更有利

模式1。与助手一起

应用程序辅助程序

def user_link(username)
    link_to User.find_by_username(username).user_profile.nickname, show_user_path(username)
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 %>

试试看

#主题模型
#通孔镜
范围:获取主题列表,lambda do
订单(“更新的描述”)。连接(:注释线程=>:用户)。限制(100)
结束
#via方法
def self.get_主题_列表
Topic.order(“updated_at DESC”).joins(:comment_threads=>:user)。限制(100)
结束
#在控制器中或移动到模型本身(推荐)
@topics=Topic.get\u Topic\u列表
#在你看来

这是干什么用的?它会更快吗?它试图用更少的查询从数据库中获取所有数据。。使用原始代码,您将对数据库进行大量查询。。再见,谢谢。所以,当我想通过嵌套列约束记录时,我应该使用include还是joins??这就是你的意思吗?如果是这样的话,include还是join,哪一个更好??不要忘记新的约定;)<代码>注释线程:true。旧的散列语法已经被淘汰了,其实差别不大。。在视图中查看SQL?为了你自己,改掉那个习惯。所有这些查找程序代码都应该在您的模型中,而不是在应用程序控制器中,尤其是在视图中。@Daimen感谢您的建议!但是,如果我用Model做这件事,你怎么能编码呢?你要做的是在你的主题模型中有一个名为
recent
的方法,这样你就可以执行如下操作:
@topics.recent
。您还可以创建一个命名范围。
<% @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 %>
# 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 %>