新手问题 有一个菜单的循环请教

1272729223 · April 14, 2013 · Last by 1272729223 replied at April 14, 2013 · 2317 hits

目前菜单有固定的几个大分类: Wedding,Lover,Family,Girl,Portrait,Personal

我是直接在 album 的 model 里面写了 CATEGORIES 的常量。 然后吧@albums循环出来对应具体的 category。

- @albums.each do |album|
  - case album.category
  - when "wedding"
    = link_to album.title, album
  - when "lover"
    = link_to album.title, album
  - when "family"
    = link_to album.title, album
  - when "girl"
    = link_to album.title, album
  - when "portrait"
    = link_to album.title, album
  - when "personal"
    = link_to album.title, album

但是最终的效果我想要的是:

dl.nav
  dt.wedding Wedding
  dd
     = link_to "wedding1"
     = link_to "wedding2"
  dt.lover Lover
  dd
     = link_to "lover1"
     = link_to "lover2"
  ....

首先你的问题是什么? 其次你那个 case when 所有的 case 执行的完全一样,有什么意义呢?

#1 楼 @blacktulip 不一样的,每个album都有一个自己的 category。在创建album的时候对应上去的。

但是现在这种方式写循环出来的结果是:

dl.nav
  dt.wedding Wedding    #重复
  dd                               #重复
     = "wedding1"
  dt.wedding Wedding    #重复
  dd                              #重复
     = "weddding2"

等于不得不把dt dd重复循环出来。

实际想要的效果是:

dl.nav
   dt.wedding Wedding
   dd
     = "wedding1"
     = "wedding2"
     = "wedding3"

lz 尝试下 Array#group_by

#3 楼 @iBachue

.navbar
  = link_to "summer", root_path, :class => "brand"
  dl.nav
    - @albums.group_by(&:category) do |category, albums|
      - case category
      - when "wedding"
        dt.wedding Wedding
        dd
          - albums.each do |album|
            = link_to album.title
      - when "lover"
        dt.lover Lover
        dd
          - albums.each do |album|
            = link_to album.title
      - when "girl"
        dt.girl Girl
        dd
          - albums.each do |album|
            = link_to album.title
      - when "family"
        dt.family Family
        dd
          - albums.each do |album|
            = link_to album.title
      - when "portrait"
        dt.portrait Portrait
        dd
          - albums.each do |album|
            = link_to album.title
      - when "personal"
        dt.personal Personal
        dd
          - albums.each do |album|
            = link_to album.title

我这里哪里写错了吗?

/Users/yuwen/Documents/rails-apps/summer/app/views/shared/_navbar.html.slim:36: both block arg and actual block given
Extracted source (around line #36):

33:         dd
34:           - albums.each do |album|
35:             = link_to album.title

解决了 漏写了一个 each,晕死了。

- @albums.group_by(&:category).each do |category, albums|

这样做不行,还是以上那个,我再想想精简一下。

该条信息已经重新编辑过

You need to Sign in before reply, if you don't have an account, please Sign up first.