views:

323

answers:

1

I have an active record class

  class Service_Catalogue < ActiveRecord::Base
    set_table_name  "service_catalogue"
    set_primary_key "myKey"
  end

myKey is an nvarchar (sql server).

When I try and save it

  service_catalogue= Service_Catalogue.new()
  service_catalogue.myKey = "somevalue"
  service_catalogue.save

I get the following error:

  IDENTITY_INSERT could not be turned OFF for table [service_catalogue] (ActiveRecord::ActiveRecordError)

It seems like ActiveRecord thinks that the primary key is an identity column (it's not its a varchar) and so is failing.

Is there a way to tell it not to try and turn off identity insert?

UPDATE

It turns out the version of the active record sql server adapter was to blame. I had previously been using 1.0.0.9250 but somehow 2.2.19 got installed (I presume when doing a gem update). After reverting to the old version it works fine.

+3  A: 

ActiveRecord likes to have integer ID columns and throws a fit if this is not the case. It can be coached to deal with alternatives, but this depends on your environment.

An alternative is to have a conventional integer-based ID field, and a unique "key" field that is used for lookups.

class Service_Catalogue < ActiveRecord::Base
  set_table_name  "service_catalogue"

  validates_uniqueness_of :myKey
end

If it's possible, it might be more convenient to alter your schema to fit ActiveRecord than to coach ActiveRecord to deal with your schema. If not, you might need to really get down and dirty.

Another approach could be to use an alternative ORM like DataMapper which does not have the same limitations.

tadman
thanks for the suggestion. unfortunately this is a system that I cannot change and have to use AR on.I found the solution anyway and have updated the answer with it.
Derek Ekins