在 Ruby on Rails 中循环对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6085661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:12:50  来源:igfitidea点击:

Loop over Object attributes in Ruby on Rails

ruby-on-railsruby-on-rails-3

提问by Robert B

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.

是否可以在 Rails 中循环对象的属性?我有一个对象,而不是在视图中编码每个属性,我想在视图中输出每个属性,因为有很多。

I have an object called @work_profilewhich has many attributes, mainly boolean check box values.

我有一个名为的对象@work_profile,它具有许多属性,主要是布尔复选框值。

Edit: I see I can use @work_profile.attributes. Any help on formatting the hash into something more user friendly would be great.

编辑:我看到我可以使用@work_profile.attributes. 任何关于将哈希格式化为更用户友好的东西的帮助都会很棒。

回答by mbreining

The ActiveRecord::Base.attributes()method returns a hash of all the attributes. You can use that to loop over all attributes.

ActiveRecord的:: Base.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 %>