Rails在列表的末尾显示哈希值

时间:2013-01-11 15:19:27

标签: ruby-on-rails-3 list alphabetical

我正在运行Rails 3.2.11。我有一篇文章模型:

class Article < ActiveRecord::Base
  attr_accessible :content, :name
end

我的控制器(索引操作)是:

class ArticlesController&lt; ApplicationController中

  def index
    @grouped = {}
    Article.all.each do |article|
      letter = article.name.slice(0,1)
      @grouped[letter] ||= []
      @grouped[letter] << article
    end
  end

这将为概述页面创建所有文章名称的字母顺序列表。 index.html.haml是:

%p
  %ul
    - @grouped.keys.sort.each do |letter|
      %h1
        = letter
      %ul
        = @grouped[letter].each do |article|
          %li
            = link_to article.name, article

现在我得到了所有文章名称的列表,按字母排序,但在某个字母的所有文章的末尾,这里是一个显示所有数据的哈希:

A

- Albert
- Altman
- Armstrong
[#<Article id: 3, name: "Albert", content: "dpio osahu psauhd asuhd psauh piuh asuhd uh isah iu...", created_at: "2013-01-11 11:51:30", updated_at: "2013-01-11 11:51:30">, #<Article id: 6, name: "Altman", content: "aosdi asoijd poisajpo isajdpoia sjdpoia jsapoij sap...", created_at: "2013-01-11 12:36:10", updated_at: "2013-01-11 12:36:10">, #<Article id: 7, name: "Armstrong", content: "osfduhsdo sdpiuh dspiufh sdpioufhsdioufh sdpiufh sd...", created_at: "2013-01-11 12:42:08", updated_at: "2013-01-11 12:42:08">]

如何摆脱最后的哈希?

1 个答案:

答案 0 :(得分:3)

= @grouped[letter].each do |article|

用此

替换该行
- @grouped[letter].each do |article|

each返回它迭代的集合。您不需要打印它,您已经打印了所有单个元素。