Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Wednesday, September 19, 2007

Ruby on Rails - Legacy MySQL Database

I'm rewriting a company admin tool written in mod_perl (Catalyst) and replacing it with a new one using Ruby on Rails. At the moment, I have to keep the legacy database/schema. Most of the old tables don't use auto-incrementing keys, which means I won't get the Rails Active::Record magic and I need to work around the keys.

Here's an example table:

mysql> describe clients;
| Field | Type | Null | Key | Default | Extra |
| client_abbrv | varchar(5) | NO | PRI | | |
| client_name | varchar(50) | YES | | NULL | |

To get this to work with Rails, I had to make a few small changes.

I made one small change in the view, which was setting the name of the primary key field. I changed "client_abbrv" to "id" in the form:


<%= error_messages_for 'client' %>

<legend>Add a Client
<% form_tag :action => "create" do %>
<label for="client_client_name">Client Name:
<%= text_field 'client', 'client_name' %>
<label for="client_id">Client Abbrv:
<%= text_field 'client', 'id' %>
<%= submit_tag 'Add' %>
<% end %>

For the model, I had set the primary key with set_primary_key.


class Client < ActiveRecord::Base
set_primary_key "client_abbrv"

Luckily, the table was already pluralized. If it had been "client," then I would have had to add this line:

def self.table_name() "client" end

For the controller, I had to change the create method:


def create
@client = = params[:client][:id]
@client.client_name = params[:client][:client_name]
flash[:notice] = "Client was successfully created."
redirect_to :action => 'list'
render :action => 'new'

That replaced the old create method where I had the normal:

@client =[:client])

When using set_primary_key, you insert data using "id" and typically select data using the actual field name, "client_abbrv" in this case.

Here's what the controller is doing for the create method:

dsparling-imbps-computer:~/my/rubydev/uclick-admin dsparlingimbp$ script/console
Loading development environment.
>> client =
=> #<Client:0x32b5e14 @new_record=true, @attributes={"client_name"=>nil}>
>> = "abc"
=> "abc"
>> client.client_name = "ABC Company"
=> "ABC Company"
>> client.valid?
=> true
=> true

Saturday, September 1, 2007

Upgrading to PHP5 on Mac OS X 10.4

I've been running PHP5 for ages on my Linux box, but my new (for me) MacBook Pro had, time for an upgrade. Well, easy enough...

I downloaded the PHP5 tarball from and did the install.

Before the install, I commented out all the php4 lines in my apache config file(/etc/httpd/httpd.conf).

The entropy package installed under /usr/local/php5 and it added a new config file (/private/etc/httpd/users/+entropy-php.conf), which is included by the main apache httpd.conf file...restart apache, that's it!

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.