Ruby on Rails HTML-Table Generator

chrishomer picture chrishomer · Jul 16, 2009 · Viewed 17k times · Source

I am looking for a good RoR table generator (or an easy solution) that can give me a decent view of my records in a table (unstylized but proper strict XHTML).

Let's say I have a User model and an Address model: - A User can have many Addresses - One address is also linked as the "primary_address"

Let's say I have the following in my User controller

def index
   @users = User.find(:all,:order => 'id ASC')
   @headers = ["id","First","Last","City","State"]
   @fields = [:id,:firstname,:lastname,:primary_address.city,:primary_address.state]
end

I don't know if the array of fields would work but I think it gets the point across. Does anyone know a good gem, plugin or technique for this so that I don't have to "repeat myself" on all my table views?

Answer

Ninad picture Ninad · Jul 31, 2010

@ChrisH: Representing table using two arrays won't give more control. I would suggest the following: table_helper

erb snippet -

collection_table(@posts, {}, :id => 'posts', :class => 'summary') do |header, body|
  header.column :title
  header.column :category
  header.column :author
  header.column :publish_date, 'Date< br \>Published'
  header.column :num_comments, '# Comments'
  header.column :num_trackbacks, '# Trackbacks'

  body.alternate = true
  body.build do |row, post, index|
    row.category       post.category.name
    row.author         post.author.name
    row.publish_date   time_ago_in_words(post.published_on)
    row.num_comments   post.comments.empty? ? '-' : post.comments.size
    row.num_trackbacks post.trackbacks.empty? ? '-' : post.trackbacks.size
  end
end