从模型轨道中抓取最新的3条记录

时间:2021-11-07 12:39:51

Just wondering if there is a more efficient way of handling the following query, within my controller i have

只是想知道在我的控制器中是否有更有效的方法来处理以下查询

@latest = Portfolio.limit(3).order('taken desc')

to extract the latest 3 records from my model.

从我的模型中提取最新的3条记录。

Is there a more efficient query that could handle this, would the query be better served within a scope in the model?

是否有更高效的查询可以处理这个问题,是否可以在模型的范围内更好地提供查询?

Advice appreciated

建议表示赞赏

Thanks

谢谢

1 个解决方案

#1


3  

Something like this should work fine

像这样的东西应该可以正常工作

class Portfolio < ActiveRecord::Base
  scope :last_three_taken, -> { order('taken desc').limit(3) }
end

This would make your controller more indipendent from the database logic:

这将使您的控制器与数据库逻辑更加独立:

@latest = Portfolio.last_three_taken

So, it wouldn't be a much more efficient from a performance point of view, but it gains a much better MVC separation in my opinion.

因此,从性能的角度来看,它不会更有效,但在我看来,它获得了更好的MVC分离。

#1


3  

Something like this should work fine

像这样的东西应该可以正常工作

class Portfolio < ActiveRecord::Base
  scope :last_three_taken, -> { order('taken desc').limit(3) }
end

This would make your controller more indipendent from the database logic:

这将使您的控制器与数据库逻辑更加独立:

@latest = Portfolio.last_three_taken

So, it wouldn't be a much more efficient from a performance point of view, but it gains a much better MVC separation in my opinion.

因此,从性能的角度来看,它不会更有效,但在我看来,它获得了更好的MVC分离。