Using Rails can be fun, however sometimes you have a legacy Oracle table that is bringing you down. This table was possibly created long ago, and does not have a sequence setup to handle the primary key. Since Oracle has no auto number type this can be a problem. Rails usually would have a hard time with this since it likes to stick to it’s “sensible defaults”. However, if we set a few things manually we can whip Rails and Oracle into shape.
First thing we need to do is set the table_name and primary_key attributes for our legacy table. Then we need to set the before_save property to increment our column id by selecting the highest legacy id and adding one to it. Pretty simple.
class LegacyTable < ActiveRecord::Base
self.table_name = 'crappy_legacy_table'
self.primary_key = 'legacy_id_column'
attr_accessible :legacy_id_column, :another_column, :yet_another_column
self[:legacy_id_column] = LegacyTable.select(:legacy_id_column).order('legacy_id_column desc').first.legacy_id_column.to_i + 1
This is for sure not a best practice, but if you cannot create a sequence and need rails to work with legacy oracle, this will do the trick.