无需硬编码即可动态提取列名

Extract column names dynamically without having to hardcode

我正在构建一个显示数据库中所有 table 的管理页面。我想在不对列名进行硬编码的情况下这样做。现在,我在我的视图中对值进行硬编码,以便它显示来自数据库 table 的值。我怎样才能从数据库中提取列名而不必对列名进行硬编码并以 table 格式打印它们。这样即使我有 10 个 tables,我也可以调用 table 并打印提取信息的列名。

代码如下:

型号:

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>

您可以使用 #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>

使用Product.column_names。所以为了你的目的,

<% Product.column_names.each do |column_name| %>
  <tr class="success">
    <th><%= column_name %></th>
  </tr>
<% end %>

我会为此做一部分。

#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} %>

或您拥有的任何其他东西。