如何更改最终出现在列表中的项目数

How can I change the number of items that end up in a list

我正在研究一个 rails 项目,我想修改最终出现在特定页面上的项目数。该页面通过一系列项目填充。

我一直想不出如何让它只显示 2 个而不是 4 个项目。

在 haml 文件中有这一部分:

%ul.story-list
- @stories.each do |story|
  %li
    - unless story.image.blank?
      .img-container{ class: ((story.video.blank?)? "": "video-container") }
        = image_tag(story.image_url, alt: story.name, class: ((story.video.blank?)? "": "js-has-video"), :video => story.video)
    .story-data
      %h4= story.name
      %h5.location= story.location
      %p.quote= story.story
      - if story.get_connected?
        = link_to 'Get Connected', connect_path
      - elsif story.gather_supplies?
        = link_to 'Gather Supplies', supplies_path
      - elsif story.make_a_plan?
        = link_to 'Make a plan', plan_path

页面显示(在服务器上)有四个故事项目,我希望它只显示两个。我期待打开 haml 文件并删除一些行(或将它们注释掉)。我很困惑。

所以,我怀疑故事的数量来自控制器或类似的东西。 ..但也许它来自服务器上的占位符数据?

如果你有灵感帮助我,所有代码都在这里 https://github.com/city72/city-72

我要修改的确切页面是这一页,我希望它只有两个故事: http://collier72.herokuapp.com/stories

奇怪的是,在我的本地环境中我根本无法编辑故事。这就是让我认为项目数量来自数据的原因。

故事控制器是这个没有指定故事数量的小文件:

class StoriesController < ApplicationController

  after_filter :static_content

  def index
    all_stories = EmergencyStory.order("index,id ASC").all
    @selected_story = all_stories.select {|s| s.selected}.first
    @stories = all_stories.collect.select {|s| !s.selected}
  end

end

打开这个文件:

https://github.com/city72/city-72/blob/master/app/controllers/stories_controller.rb#L8

从下面更改该行:

@stories = all_stories.collect.select {|s| !s.selected}

对此:

@stories = all_stories.collect.select{|s| !s.selected}.slice(0,2)

据我所知,returning 4 并不是故意的,它只是数据库中的内容。 slice(0,2) 将 return 前两项。

首先,您有 3 个故事要查找,而不是 2 个。您有 @selected_story,然后是剩余的 @stories。其次,当您在数据库中获取很多故事时,您正在检索所有不会缩放的故事,因此渲染此页面会随着时间的推移而变慢。所以你需要限制数据库返回的记录数。

获取所选故事。 然后获取接下来的两个故事。

class StoriesController < ApplicationController
  after_filter :static_content
  def index
    @selected_story = EmergencyStory.where(selected: true).first
    @stories = EmergencyStory.where(selected: false) # don't get selected
                             .limit(2) # limit records returned
                             .order("index,id ASC")
                             .all
  end
end

如果您要进一步完善它,您应该将这两个查询放入方法中 EmergencyStory

class StoriesController < ApplicationController
  after_filter :static_content
  def index
    @selected_story = EmergencyStory.selected_story
    @stories = EmergencyStory.recent_stories
  end
end

class EmergencyStory < ActiveRecord::Base
   def self.selected_story
     where(selected: true).first
   end

   def self.recent_stories
     where(selected: false).limit(2).order('index,id ASC').all
   end
end