【发布时间】: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 # < Class:0x4ab7af0>
【问题讨论】:
-
您可以使用
rails_admin、active_admin或我的简单库bareback来完成此任务,请查看github.com/nielsbuus/bareback
标签: ruby-on-rails database ruby-on-rails-4 activerecord