View All of Your Database Tables in Rails
Posted: May 18th, 2009 | Author: admin | Filed under: Rails | Tags: database, models, Rails, ruby on rails | No Comments »When working on a Ruby on Rails project, you often find yourself needing to see what the names of the columns in your tables are. This can be done by simply looking at your migration files, but after several migrations in, this can be a confusing headache. This is my very simple solution to seeing all of the tables listed on one page in my project.
1. Create a New View
I called mine models.html.erb. Paste in the folling code:
<% @models.each do |model| %>
<h3 style="margin:0;padding:0"><%=h model %></h3>
<table width="400">
<% model.constantize.columns.each do |col| %>
<tr>
<td><b><%=h col.name %></b></td><td><%=h col.sql_type %></td><td><%=h col.default.to_s %></td>
</tr>
<% end %>
</table>
<br />
<% end %>
2. Add Your Models in the Controller
Go to the controller that is part of your view and add the corresponding method. In the method you just need to add a line telling it the names of all of your models. For example:
@models = ['User','Article','Subject']
3. Take a Look!
The resulting table will have 3 columns: the name of the column in the database, the data type, and the default value (if one exists).
