2014-11-23 55 views
1

在我的应用的管理面板中,我想显示数据库中的所有表。在Rails控制器中获取数据库中的所有表

的方式我这样做此刻正让所有的记录为每个表,如:

@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.. 

我想这样做是为了得到一个散列关闭所有T ABLES这样的:

@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

你可以用'rails_admin','active_admin'或我的简单库'bareback'执行此任务,请查看https://github.com/nielsbuus/bareback – 2014-11-23 15:19:10

回答

1

没关系.. 看来我是错过了.all

正确的呼叫:@DB["User"].all.each

相关问题