Ruby on rails Rails-避免在表中重复
我有一个数据表,其中我遍历了每个用户属性,并将其显示在一个表中。这似乎有很多重复,即使单词不一样,每个属性的过程也是一样的。是否有一种方法可以自动生成一个标题为Ruby on rails Rails-避免在表中重复,ruby-on-rails,dry,Ruby On Rails,Dry,我有一个数据表,其中我遍历了每个用户属性,并将其显示在一个表中。这似乎有很多重复,即使单词不一样,每个属性的过程也是一样的。是否有一种方法可以自动生成一个标题为attribute.titleize且数据单元为user.attribute的表行 %table %tr %th First Name %td= @user.first_name %tr %th Middle Name %td= @user.middle_name %tr %th Las
attribute.titleize
且数据单元为user.attribute
的表行
%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
也许你可以用一个局部的
您可以将
\u属性设置为部分属性,以呈现表格的一行:
# 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
非常感谢你的回答。我从未想过以这种方式使用partial,仍然在学习收集方面。几分钟后我会记下答案的。不客气。我用一个选择属性子集的方法示例更新了我的答案,如果您需要的话。