Mass Update / Initialize Database Field

I have a field that I need to mass update and I was looking for an efficient way to update them.  I found it with “update_all”.  By doing:

Model.update_all :field=>value

It will update all of the records to the value you want.  If you want to do it for only certain records, you can use a where clause like so:

Model.where(“foo = ?”, “bar”).update_all :field=>value


Setting Default Values for Rails Fields

For some fields, you may want to set default values for when a new record is created.  For example, if you want to set a flag/boolean field to true or false when a new record is created.  An easy way to do this is through a migration.

If you are just creating the field, you can do:

def change
add_column :table_name, :field_name, :field_type, :default => 0
add_column :table_name, :field_name, :field_type, :default => true

To edit an existing field:

def up
change_column :table_name, :field_name, :boolean, :default => true

Switching from jQGrid to Data Tables

Was finding using jQGrid was becoming way more complicated than it should be. Moved to data tables, which also runs on jQuery. For me, what was nice was that someone did a tutorial on how to integrate it with Twitter Bootstrap (which I was already using) to make it look good as well. If you don’t use Twitter Bootstrap, you can also use the jQuery UI roller to make a style and color scheme to make the table look nice.

Data tables included the functionality I needed – search and pagination and all I had to do was point the javascript to my html table code. Simple.

CSV Export

One gem to use to allow users to export table data, like reports, is FasterCSV.  The only thing is that there isn’t a lot of documentation on it.  Here is a great tutorial on it:

The only minor issue I ran into was that I needed to add this line:
@output_encoding = ‘UTF-8’

under the format.csv part, like so:

format.csv do
@output_encoding = ‘UTF-8’