在 Ruby on Rails 中循环对象属性 [英] Loop over Object attributes in Ruby on Rails
问题描述
是否可以在 Rails 中遍历对象的属性?我有一个对象,而不是在视图中编码每个属性,我想在视图中输出每个属性,因为有很多.
我有一个名为 @work_profile
的对象,它有很多属性,主要是布尔复选框值.
我知道我可以使用 @work_profile.attributes
.任何有关将哈希格式化为对用户更友好的内容的帮助都会很棒.
ActiveRecord::Base.attributes() 方法返回所有属性的哈希值.您可以使用它来遍历所有属性.
@work_profile.attributes.each do |attr_name, attr_value|...结尾
在一个视图中,这将给出:
<% @work_profile.attributes.each do |attr_name, attr_value|%><div class="work_profile_attribute"><%= attr_name %>:<%= attr_value %>
<%结束%>
Is it possible to loop over an object's attributes in Rails? I have an object and rather than code up each attribute in the view, I want to output each of them in the view as there are quite a few.
I have an object called @work_profile
which has many attributes, mainly boolean check box values.
Edit: I see I can use @work_profile.attributes
. Any help on formatting the hash into something more user friendly would be great.
The ActiveRecord::Base.attributes() method returns a hash of all the attributes. You can use that to loop over all attributes.
@work_profile.attributes.each do |attr_name, attr_value|
...
end
In a view, this would give:
<% @work_profile.attributes.each do |attr_name, attr_value| %>
<div class="work_profile_attribute">
<%= attr_name %>: <%= attr_value %>
</div>
<% end %>
这篇关于在 Ruby on Rails 中循环对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!