Sunday, May 13, 2012

Using Legacy MS SQL Server 2008 tables with Ruby on Rails Application

On my first Rails application I’m developing against a legacy MS SQL Server database running on MSSQL R2. When I developed this database back in 2001 I didn’t follow any of the Rails “opinions” in terms of column naming. This makes working with the database somewhat difficult.
I found a presentation from the 2009 Rails Conference entitled “Rails + Legacy Databases” which provided some great tips. One of the suggestions for working with a MSSQL database and tables that don’t match the Rails convention is to use a database view to simulate the table with the Rails naming.
I thought this was pretty slick, but I wasn’t able to get it to work at the outset. I contacted the presentation author Brian Hogan a few times via Twitter and he advised meto make sure of two things to make this work: 1.) Make sure the view is updatable, which is a permission you have to make sure the SQL login account that your Rails app is using to connect has. Here’s the SQL code that I used to create the view with the permissions my Rails login needed:
use [hla]
GO
GRANT DELETE ON [dbo].[States] TO [hlaapprailsuser]
GO
use [hla]
GO
GRANT INSERT ON [dbo].[States] TO [hlaapprailsuser]
GO
use [hla]
GO
GRANT SELECT ON [dbo].[States] TO [hlaapprailsuser]
GO
use [hla]
GO
GRANT UPDATE ON [dbo].[States] TO [hlaapprailsuser]
GO
2.) Make use of the
:foreign_key => "state_id"
parameter on your associations.
This ended up working out really nice and saved me time and headache so I thought I would share in case anyone else finds themselves in a similar circumstance.

No comments: