Skip to content

Instantly share code, notes, and snippets.

@dtom90
Created March 16, 2017 00:21
Show Gist options
  • Save dtom90/56b82bf15fa0bffa2e3b81901e1cbe26 to your computer and use it in GitHub Desktop.
Save dtom90/56b82bf15fa0bffa2e3b81901e1cbe26 to your computer and use it in GitHub Desktop.
Rails Partial to display table of ActiveRecord::Relation
<% columns = records.klass.columns.map {|col| col.name} %>
<% columns = columns - blacklist if defined? blacklist %>
<table class="table table-bordered table-striped">
<tr>
<% columns.each do |col| %>
<th><%= records.klass.human_attribute_name col %></th>
<% end %>
<% helpers.each do |helper| %>
<th><%= records.klass.human_attribute_name helper %></th>
<% end %>
</tr>
<% records.each do |rec| %>
<tr>
<% columns.each do |col| %>
<td><%= rec[col] %></td>
<% end %>
<% helpers.each do |helper| %>
<%= method(helper).call(rec) %>
<% end %>
</tr>
<% end %>
</table>
@dtom90
Copy link
Author

dtom90 commented Mar 16, 2017

Can be rendered within a view with something like:

<%= render partial: 'layouts/record_table', locals: { 
    records: Messages.all,
    helpers: %w(colored_table_cell button_table_cell),
    blacklist: %w(id created_at updated_at)
} %>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment