好的,我确定我在这里遗漏了一些东西,但请原谅我,我是Rails的新手。
Rails中是否有某种方法可以显示对象的所有字段而不是指定每个字段?
在我的show.html模板中,而不是
<p>Name: <%=h @user.full_name %></p>
<p>Email: <%=h @user.email %></p>
我只想要一个oneliner来做这个,而不必输入我所拥有的15个左右的字段。 它是一个管理页面,如果显示所有字段(id,created_at等),它就很好 如果这是PHP,使用foreach需要大约5秒钟,但是我用Google搜索(显然是错误的)一小时没有运气。
谢谢!
答案 0 :(得分:36)
像
这样的东西<% for attribute in @user.attributes.keys %>
<p><%= attribute.humanize %> <%= @user.attributes[attribute].to_s %></p>
<% end %>
可以做到这一点。
马特
答案 1 :(得分:4)
我想你想要显示数据库表中一行的所有属性,这些属性被定义为ActiveRecord模型。您可以使用类方法 column_names (每个ActiveRecord模型都有它),它返回数组中表列的名称。
<%= User.column_names.collect { |col_name| "#{col_name.capitalize}: <p>#{@user[col_name]}</p>" }.join("\n") %>
答案 2 :(得分:2)
<%= debug @user %>
显示对象的简单方法......这就是我通常使用的方式!
答案 3 :(得分:0)
@user.attributes.each{|key, value| puts "#{key} : #{value}"}
答案 4 :(得分:0)
这是我用来将一些我不想展示的属性列入黑名单的片段......
controller(user_controller.rb)
def show
keys_blacklist = %W(user_id name) #these are the fields to hide
@user_showlist = @user.attributes.except(*keys_blacklist)
end
查看(show.html.erb):
<!-- language: ruby --><% for attribute in @user_showlist.keys %>
<b><%= attribute.humanize %></b>
<%= @user.attributes[attribute].to_s %>
<!-- language: ruby --><% end %>
您也可以使用:
@user_showlist = @user.attributes.slice(*keys_whitelist)
以显示属性的列表。
答案 5 :(得分:0)
如果您正在使用haml并想要遍历视图中的用户对象上的属性:
public enum KDErrors {
KDR_280(280, "Blue"),
KDR_281(281, "Red"),
KDR_282(282, "Green"),
KDR_284(284, "Yellow");
private final int code;
private final String color;
private KDErrors(int code, String color) {
this.code = code;
this.color = color;
}
public static String getColorByCode(int colorCode) {
return ???
}
}