ruby-on-rails - 无需硬编码即可动态提取列名

标签 ruby-on-rails ruby ruby-on-rails-3 sqlite ruby-on-rails-4

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

代码如下:

型号:

class Product < ActiveRecord::Base
end

Controller :

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>

关于ruby-on-rails - 无需硬编码即可动态提取列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610070/

相关文章:

ruby:如何获取当前类而不是基类中定义或覆盖的所有方法?

ruby-on-rails - Ruby on Rails - RSpec - 重构 lambda 样式测试

ruby-on-rails - 测试属于 Rails 中帖子的评论的 Controller

ruby-on-rails - 如何从目录中获取文件名和扩展名

ruby-on-rails - Ubuntu 10 ruby 1.9 Rails 3 : No such file or directory

ruby-on-rails - rails : Storing a 256 bit checksum as binary in database

ruby - 如何将字符代码转换回字符?

ruby-on-rails - 如何使用 Ruby on Rails 从电子邮件中提取所有 URls/链接?

ruby-on-rails - 未定义的方法 `permit' 为 "1":String - RSPEC

ruby-on-rails - 创建新的 Rails 应用程序时,为什么会出现 Gemfile.lock 文件而不运行 bundle 安装?