2012-11-06 31 views
1

我有,我经过每一个用户属性数据的表重复,并在表中显示。这似乎是一个大量的重复,尽管话是不一样的,每个属性的过程。有没有一种方法可以自动使用attribute.titleize头和user.attribute数据单元的表行?Rails的 - 避免在表

%table 
    %tr 
    %th First Name 
    %td= @user.first_name 
    %tr 
    %th Middle Name 
    %td= @user.middle_name 
    %tr 
    %th Last Name 
    %td= @user.last_name 

回答

2

你可以做一个_attribute部分呈现表的单行:

# app/views/users/_attribute.html.haml 
%tr 
    %th= attribute.first.titleize 
    %td= attribute.second 

# app/views/users/show.html.haml 
%table 
    %tbody= render partial: 'attribute', collection: @user.attributes.to_a 

如果你不想渲染User每个属性,创建模型上的方法返回你想要的属性,而不是@user.attributes

# app/models/user.rb 
class User 
    def public_attributes 
    attributes.slice('first_name', 'middle_name', 'last_name') 
    end 
end 
+0

非常感谢你这个答案。我从来没有想过以这种方式使用部分,仍然在学习集合方面。几分钟后,我会标记为答案。 – ardavis

+1

不客气。如果你需要的话,我用一个选择属性子集的方法来更新我的答案。 – Brandan