Synthesis : Scott Becker

RoR Grid Control Part II

My reusable “grid control” with paging and filtering is almost finished. I made some changes to the syntax, and I converted the whole thing to a component, so it can simply be dropped in the components directory of a rails app and used as is.

Defining the columns is very DRY, the minimum thing you have to specify for each column is a title. From this the component will guess the actual database column to be the same (with spaces converted to underscores). If your database column name is different, you can specify that.

I also added some display format options, including “email”, “website” and “money” and “date”. These will make the columns look and behave as you would expect.

Here’s what the code to call it looks like now:

  def my_controller_method
    grid_html = render_component_as_string(:controller => 'controls/grid', :action => 'grid',
      :params => {
        :model => Product,
        :obj => params[:obj],
        :columns => [
          { :title => "Category",
             :db_column => "category_name",
             :filter_type => :select,
             :filter_column => "category_id",
             :filter_options => Category.find(:all, :order => "name ASC").collect {|c| [ c.name, c.id ] }
          },
          { :title => "Name" },
          { :title => "Published",
             :filter_type => :select,
             :filter_options => Product.published_options
          },
          { :title => "Featured",
             :filter_type => :select,
             :filter_options => Product.featured_options
          },
          { :title => "Retail", 
             :db_column => "retail_price", 
             :format => :money, 
             :filter => :false 
          },
          { :title => "Stock", 
             :db_column => "in_stock", 
             :filter => :false }
        ],
        :joins => ["LEFT OUTER JOIN categories ON products.category_id = categories.id"],
        :alias_columns => [["categories.name", "category_name"]],
        :order_by => "category_name, products.name",
        :per_page => 25
      })
    render :text => grid_html, :layout => true
  end

Once I get everything reasonably ironed out and add a few more things like sorting, I plan to open source this code…

Again, here is what mine looks like. This could easily be customized to look any way you want, by simply modifying the view rhtml file:

 

Comments are closed.