rails3 will_paginate hash object

2020-02-29 16:37发布

问题:

Looks like will_paginate dosen't support paginating a hash object. I have a list of articles which is basically a collection of yaml files that i want to output on a page.

def index
  @articles = Dir["#{Rails.root}/blog_articles/*.yml"].inject({}) do |h, file|
    h["#{File.basename(file, '.yml')}"] = YAML::load(File.open(file))
    h
  end
end

Can anyone suggest me on how to write the pagination for this? Thanks.

回答1:

In your controller:

def index 
  @articles = Dir["#{Rails.root}/blog_articles/*.yml"].inject({}) do |h, file|   
    h["#{File.basename(file, '.yml')}"] = YAML::load(File.open(file)) 
    h 
  end 

  # paginate the keys of the hash instead of the hash itself
  @article_keys = @articles.keys.paginate
end    

In your views:

<% @article_keys.each do |k| %>
  <%= @articles[k] %>