【问题标题】:Get all tables from database in Rails controller在 Rails 控制器中从数据库中获取所有表
【发布时间】:2015-01-21 07:22:28
【问题描述】:

在我的应用程序的管理面板中,我想显示数据库中的所有表。

我目前这样做的方式是获取每个表的所有记录,例如:

@users = User.all
@pages = Page.all
etc.

我在视图中创建了一个表,手动添加表头:

<thead>
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Email</th>
  </tr>
</thead>

我访问所有记录:

<% @users.each do |user| %>
        <tr>
            <td><%= user.id %></td>
etc..

我想做的是像这样从所有表中获取哈希:

@DB is { table_name_1: table_object_1, table_name_2: table_object_2}

那么在我看来,我可以做类似的事情

<% @DB.each do |table| %>
    <table>
        <% @table.each do |record| %>
        <table row>
        <%end%>
    </table>
<%end%>

我设法使用这个来获取表名:

@DB = Hash.new
    ActiveRecord::Base.connection.tables.each do |table|
      next if table.match(/\Aschema_migrations\Z/)
      next if table.match(/\Aauthentications\Z/)
      klass = table.singularize.camelize.constantize      
      @DB[klass.name] = klass
    end
  end

从这里:How to list of all the tables defined for the database when using active record?

但是我得到@DB["User"]没有方法each的错误

或更准确地说..:undefined method each' for # &lt; Class:0x4ab7af0&gt;

【问题讨论】:

标签: ruby-on-rails database ruby-on-rails-4 activerecord


【解决方案1】:

没关系.. 似乎我错过了.all

正确的调用是:@DB["User"].all.each

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多