ruby on rails - Extract column names dynamically without having to hardcode -
ruby on rails - Extract column names dynamically without having to hardcode -
i building admin page displays tables database. want without hardcoding column names. right now, hardcoding values in view display values database table. how can extract column names db without having hardcode column names , print them in table format. way if have 10 tables, can phone call table , print column names extracting information.
here code:
model:
class product < activerecord::base end
controller:
class admincontroller < applicationcontroller def index @products = products.all end end
view:
<h3 class="sub-header">product</h3> <table border='1' class="table table-striped" width="200"> <tr class="success"> <th>id</th> <th>url</th> <th>url id</th> <th>price id</th> </tr> <% @products.each |user| %> <tr> <td><%= user.id %></td> <td><%= user.url %></td> <td><%= user.url_id %></td> <td><%= user.price_id %></td> </tr> <% end %> </table>
you can column names of model using #column_names
this:
<% user.column_names.each |column| %> <%= column %> <% end %>
you can utilize #attributes
access attributes of object, this:
<% user.attributes.each |name, value| %> <%= "#{name} : #{value}" %> <% end %>
so, next snippet serve purpose:
<h3 class="sub-header">product</h3> <table border='1' class="table table-striped" width="200"> <tr class="success"> <% doctor.column_names.each |c| %> <th><%= c.upcase %></th> <% end %> </tr> <% @products.each |user| %> <tr> <% user.attributes.each |name, value| %> <td><%= value %></td> <% end %> </tr> <% end %> </table>
ruby-on-rails ruby ruby-on-rails-3 sqlite ruby-on-rails-4
Comments
Post a Comment