-
Notifications
You must be signed in to change notification settings - Fork 22
Home
Welcome to the table_helper wiki!
So … I love this plugin. It is so useful for quickly whipping up pages to show stuff, it’s
a dream come true how easy it is. (I just hate it when I have to code HTML :) )
But … I invariably want some “derivative” columns in the table. One or more columns
that will show data that’s not part of the ActiveRecord database table, usually something
that’s calculated on the fly.
Let’s take an example – my most recent actual use case:
I have a collection of Authors. An author has_many :mods. I want to tell the users
how many mods each author has… even more, I want to tell them how many of
a specific kind of mod the author has. But this isn’t a database column, it obviously
derived from how many there actually are in the Mods table, depending on what
kind the user asked to count.
Here’s the way I’ve ended up doing it. I think it’s neat. Maybe it’s obvious, but it
took me a few goes before I realised it was this easy, so maybe this will save you something.
In the author definition I add a new attribute for this column
def Author
# (usual blah)
attr_accessor :mod_count # attribute for author table with mod count
end
Then in the controller you can do the data collection, just as you’re supposed to
do in controllers:
def AuthorsController < ApplicationController
# GET /authors?game_type=game_type_id
# Display the number of mods the author has of the chosen game_type
def index
@game_type_id = params[:game_type]
@authors = Author.all
@authors.each {|a| a.mod_count = a.mods.find_all{|m| m.game_type_id = @game_type_id}.length}
end
end
#etc...
And in the view you can just use this attribute as if it was any other… even though it’s not a database column etc
(Note: to make this work, you do have to explicitly tell table_helper what columns you want … but that’s
no imposition because it’s usually nice to customise the column headings anyhow…)
<%= collection_table(@authors, :cellspacing=>"1px", :cellpadding=>"2px", :border=>"1") do |t|
t.header :name
t.header :mod_count, "Registered Mods"
t.header :uploaded_count, "Uploaded Mods"
t.rows.alternate = :odd
t.rows.each do |row, author, index|
row.name link_to(author.name, :controller=>:mods, :author_id=>author.id, :game_type=>@game_type_id)
end
end
%>
… notice how I didn’t have to make body row entires, it is sufficient just to call out the supplementary
columns in the header section.