Ruby-on-rails 限制每个 do 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3191448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:52:28  来源:igfitidea点击:

Limit each do loop

ruby-on-railsrubyloops

提问by Karl Entwistle

If I have the following,

如果我有以下内容,

<% @feed.sort_by{|t| - t.created_at.to_i}.each do |feed| %> 

<% end %>

How can limit it to only show the 10 most recent results

如何将其限制为仅显示 10 个最近的结果

回答by J?rg W Mittag

<% @feed.sort_by{|t| - t.created_at.to_i}.first(10).each do |feed| %>

However, it's probably best to push this down into the model like this

但是,最好将其推入这样的模型中

<% @feed.recent(10).each do |feed| %>

And, in fact, if @feedcomes out of a database, I'd push it down even further: it doesn't make sense to load a ton of unsorted feed entries out of the DB, then sort them and then throw most of them away. Better let the DB do the sorting and filtering.

而且,事实上,如果@feed来自数据库,我会将其进一步推低:从数据库中加载大量未排序的提要条目,然后对它们进行排序,然后将其中大部分扔掉是没有意义的. 最好让 DB 进行排序和过滤。

See @Peer Allan's answer for how to do it in ActiveRecord. In ARel(IOW: Rails 3) it would probably be even simpler, something like

有关如何在ActiveRecord. 在ARel(IOW: Rails 3) 中,它可能会更简单,比如

Feed.all.order('created_at DESC').take(10)

回答by Bryan Ash

Array#first(n)

数组#first(n)

[1,2,3,4,5].first(3)
=> [1,2,3]

回答by alemur

I'd do it like this:

我会这样做:

<% @array.limit(10).each do |a| %>

回答by Amadan

I agree with the others (J?rg in particular); but if you still want to know how to limit the loop itself, breakcan be useful.

我同意其他人(特别是 J?rg);但是如果您仍然想知道如何限制循环本身,break可能会很有用。

@array.each_with_index do |feed, i|
  break if i == 10;
  # ...

回答by Omer Aslam

The following code will return 10 recent records.

以下代码将返回 10 条最近的记录。

@feed = @feed.sort! { |a,b| b.created_at <=> a.created_at }.take(10)

Array Reference

数组引用

回答by Peer Allan

The created_at seems to indicate that you are using ActiveRecord in Rails to get set the @feed variable. If that is the case you are better to do this work in SQL. Its far more efficient and easier to deal with.

created_at 似乎表明您在 Rails 中使用 ActiveRecord 来设置 @feed 变量。如果是这种情况,您最好在 SQL 中完成这项工作。它更有效,更容易处理。

@feed = Feed.all(:order => 'created_at DESC', :limit => 10)

Otherwise if you really want to use the view to do this you can use first or a range

否则,如果您真的想使用视图来执行此操作,则可以使用 first 或范围

<% @feed.sort_by{|t| - t.created_at.to_i}[0..9].each do |feed| %> 
<% @feed.sort_by{|t| - t.created_at.to_i}.first(10).each do |feed| %>