我正在构建一个显示数据库中所有表的管理页面。我想这样做而不用硬编码列名。现在,我在视图中硬编码值,因此它显示数据库表中的值。如何从数据库中提取列名称而无需对列名进行硬编码,只需以表格格式打印即可。这样即使我有10个表,我也可以调用表并打印提取信息的列名。
以下是代码:
型号:
class Product < ActiveRecord::Base
end
控制器:
class AdminController < ApplicationController
def index
@products = Products.all
end
end
查看:
<h3 class="sub-header">Product</h3>
<table border='1' class="table table-striped" width="200">
<tr class="success">
<th>ID</th>
<th>url</th>
<th>url id</th>
<th>price id</th>
</tr>
<% @products.each do |user| %>
<tr>
<td><%= user.id %></td>
<td><%= user.url %></td>
<td><%= user.url_id %></td>
<td><%= user.price_id %></td>
</tr>
<% end %>
</table>
答案 0 :(得分:4)
您可以使用#column_names
获取模型的列名称,如下所示:
<% User.column_names.each do |column| %>
<%= column %>
<% end %>
您可以使用#attributes
访问对象的属性,如下所示:
<% user.attributes.each do |name, value| %>
<%= "#{name} : #{value}" %>
<% end %>
因此,以下代码段将满足您的目的:
<h3 class="sub-header">Product</h3>
<table border='1' class="table table-striped" width="200">
<tr class="success">
<% Doctor.column_names.each do |c| %>
<th><%= c.upcase %></th>
<% end %>
</tr>
<% @products.each do |user| %>
<tr>
<% user.attributes.each do |name, value| %>
<td><%= value %></td>
<% end %>
</tr>
<% end %>
</table>
答案 1 :(得分:1)
使用Product.column_names
。所以为了你的目的,
<% Product.column_names.each do |column_name| %>
<tr class="success">
<th><%= column_name %></th>
</tr>
<% end %>
答案 2 :(得分:1)
我为此做了一个部分。
#eg in app/views/common/generic_table.html.erb
<%# expects a collection of the same type of object stored in `collection` %>
<% klass = collection.first.class %>
<% column_names = klass.column_names %>
<table>
<thead>
<tr>
<% column_names.each do |colname| %>
<th><%= colname %></th>
<% end %>
</tr>
</thead>
<tbody>
<% collection.each do |obj| %>
<tr>
<% column_names.each do |colname| %>
<td><%= obj.send(colname) %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
现在您可以将其称为
<%= render :partial => "common/generic_table", :locals => {:collection => @products} %>
或其他任何你拥有的东西。