Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何限制视图中要加载的记录数???_Ruby On Rails_Ruby On Rails 3_View - Fatal编程技术网

Ruby on rails 如何限制视图中要加载的记录数???

Ruby on rails 如何限制视图中要加载的记录数???,ruby-on-rails,ruby-on-rails-3,view,Ruby On Rails,Ruby On Rails 3,View,此代码显示属于当前社区的CommunityTopic的所有记录。 如何将此处显示的记录数限制为10条 <ul> <% @community.community_topics.each do |topic| %> <li> <%= link_to topic.title, community_topic_path(@community, topic) %> <%= link_to topic.user.user_pr

此代码显示属于当前社区的CommunityTopic的所有记录。 如何将此处显示的记录数限制为10条

<ul>
  <% @community.community_topics.each do |topic| %>
    <li>
    <%= link_to topic.title, community_topic_path(@community, topic) %>
    <%= link_to topic.user.user_profile.nickname, community_topic_path(@community, topic) %>
    </li>
  <% end %>
</ul>

使用
限制
方法:

<% @community.community_topics.limit(10).each do |topic| %>

这将只向块提供集合的前10个元素。如果你想变得更复杂,你可以使用类似的东西


通常,此类数据获取应在控制器中进行。因此,与其在视图获取数据的位置使用
@community
变量,还不如使用
@community\u topics
,它预先填充了要渲染的数据。

通常不应该在视图中执行此操作,而应该在控制器中执行此操作。您可以使用@Fermaref建议的
limit
,也可以使用诸如will_paginate或kaminari之类的paginator来帮助您

要将其移动到控制器,请尝试以下操作:

def some_action
  @community = Community.find(params[:id])
  @community_topics = @community.community_topics.order(:some_attribute).limit(10)
end
然后在您的视图中使用
@community\u topics
。这里的一个优点是,您现在可以将此逻辑移动到私有方法,以便在需要时重用。您还可以在功能上测试
@community\u topics
限制为10行。

使用8.3重新排序

重新排序方法覆盖默认的范围顺序。例如:

@categories = Category.includes(:subcategories).where(active: true).references(:subcategories).order(name: :asc).reorder('categories.name ASC', 'subcategories.name ASC')

您检查过这个吗?我不应该这么做的原因是什么?如果我正在展示当前社区中的10个最新主题#show呢?我应该用这种方式吗?如果他们想看到更多,那么可以按“全部显示”并移动到CommunityTopic#索引修改/截断视图中的集合被认为是糟糕的设计,因为这会使您的逻辑更难测试、调试和重构。有时这是没有帮助的,但是渲染的数据收集尽可能属于控制器。好的,这很有意义,非常感谢!在这种情况下,如何将其替换为基于控制器?更新以澄清。请注意,我添加了一个
order
子句,这样主题将以可预测的方式返回-替换
:some_属性
。如果关联是硬编码的,以使用特定的顺序,这将是不必要的。你当然可以。出于同样的原因,这通常也会出现在控制器中。您最好使用
limit(10)
,因为
take
来自数组,所有的社区主题都会被提取到内存中,虽然只显示10条记录。因此“limit”占用的内存更少???
limit
将更改数据库查询,使其仅获取前10条记录
take
将触发查询(所有记录)以构建一个数组,然后将数组截断为前10个记录。