2012-11-06 25 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