Follow Along as I Stumble on the Path to Learning RoR

Posts tagged “field

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

Setting Field to Null in MySQL Workbench

I had some bad data in my DB where fields had a space or some other value I could not see, so I needed to set the field to null (my program looks for null).  To do this, I changed the value of the field, then clicked “Apply” and on the SQL preview screen, I changed the value to NULL (ie city = NULL where…).

Aligning Image_Submit_Tag with form elements

To align the image and form element, try:

<%= image_submit_tag “image.jpg”, :style => “position:absolute”  %>