如何显示模型中的分组行?

时间:2014-01-10 04:11:21

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

我有一个模特:

class Row < ActiveRecord::Base
    belongs_to :description
    attr_accesible :id, :q_id, :quantity, description_id
end

class Description < ActiveRecord::Base
    has_many :rows
    translate :description #globalize3, ignore it.
    attr_accesible :id, :other
end

在这种情况下,DescriptionRow具有1:N关系(N从1到3)。

在Haml中以表格格式显示此内容的最佳方法是什么?例如,如果我们在DB中:

Row:
1 | 1 | 20 | 1
2 | 2 | 22 | 1
3 | 1 | 30 | 2
4 | 3 | 31 | 2
5 | 2 | 32 | 2

Description:
1 | asd
2 | zxc

我想展示这种形式:

desc | q1 | q2 | q3 |
-----+----+----+----+
asd  | 20 | 22 | -- |
zxc  | 30 | 32 | 31 | 

更新

我添加了一个新属性(q_id),表示我的Row模型的“q”位置(1,2或3)。

2 个答案:

答案 0 :(得分:1)

在控制器代码中:

@descriptions = Description.eager_load(:rows).order('descriptions.id, rows.q_id')

在您看来:

%table
  %tr
    %th= 'desc'
    %th= 'q1'
    %th= 'q2'
    %th= 'q3'
  - @descriptions.each do |description|
    %tr
      %td= description.description
      - (0..2).each do |i| 
        %td= description.rows[i].try(:quantity) || '--'

<强>更新

如果要将行限制为特定的用户关联,可以这样执行:

@descriptions = Description.eager_load(:rows).
                  where(rows: {user_id: some_user.id}).
                  order('descriptions.id, rows.q_id')

如果您担心这可能会排除没有匹配行的描述,您可以用一个NULL替换SQL替换:

    @descriptions = Description.eager_load(:rows).
                  where('rows.user_id = ? OR rows.id IS NULL', some_user.id).
                  order('descriptions.id, rows.q_id')

答案 1 :(得分:1)

类似的东西:

%table
  %tr
    - Description.includes(:rows).find_each do |description|
      %td= description.description
      %td= format_quantity description.rows.first
      %td= format_quantity description.rows.second
      %td= format_quantity description.rows.third

辅助功能

def format_quantity(row)   
  row.present? ? row.quantity : '--' 
end

<强>更新

对于行的顺序,您可以在关系中指定

class Description < ActiveRecord::Base
    has_many :rows, order: 'q_id'