[Ruby] refactoring/drying help

Jack Danger Canty seattle.rb at 6brand.com
Thu Oct 11 15:55:12 PDT 2007


>
>
> artists:
> - first_name_last_name :string
> - writer :boolean
> - artist :boolean
>
> people:
> - first_name :string
> - last_name :string
> - full_name :string
> - rold_id :integer
>
> roles:
> 1: writer
> 2: artist



If this is in an ActiveRecord migration I'd probably do it with straight
SQL.  I've had bad experiences with relying on models in migrations when the
model code can change.


You can do it in just a couple queries:


execute " insert into people (id, first_name, last_name, role_id) select id,
substring_index(first_name_last_name, ' ', 1),
substring_index(first_name_last_ name,
' ', -1), 1 from artists where writer = 1"

execute " insert into people (id, first_name, last_name, role_id) select id,
substring_index(first_name_last_name, ' ', 1),
substring_index(first_name_last_ name,
' ', -1), 2 from artists where artist = 1"


The above assumes that role 1 is writer and role 2 is artist.


Hope this is helpful,
::Jack Danger


More information about the Ruby mailing list