从Rails控制器中获取数据库中的所有表

时间:2014-11-23 15:00:26

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

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

我现在这样做的方法是获取每个表的所有记录,例如:

@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 # < Class:0x4ab7af0>

1 个答案:

答案 0 :(得分:1)

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

正确的电话是:@DB["User"].all.each

相关问题