Lesha Pipiev
Lesha Pipiev

Reputation: 3333

Rails 3 ActiveRecord inserting autoincrement field issue

I'm using:
Rails 3.0.9
Activerecord-sqlserver-adapter 3.0.15
TinyTds
MSSQL 2005

I have following table:

CREATE TABLE [dbo].[eclaims](
    [id_app] [int] IDENTITY(1,1) NOT NULL,
    [id_user] [int] NOT NULL,
    [property] [varchar](4) NOT NULL,
    [app_number] [varchar](15) NULL,
    [patent_number] [varchar](15) NULL,
    [native_number] [varchar](20) NULL,
    [title] [nvarchar](max) NULL,
    [applicants] [nvarchar](max) NULL,
    [receive_date] [datetime] NULL,
        [change_date] [datetime] NOT NULL CONSTRAINT [DF_eclaims_change_date]  DEFAULT (getdate()),
     CONSTRAINT [PK_eclaims] PRIMARY KEY CLUSTERED 
    (
        [id_app] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO
    SET ANSI_PADDING OFF
    GO
    ALTER TABLE [dbo].[eclaims]  WITH CHECK ADD  CONSTRAINT [FK_eclaims_users] FOREIGN KEY([id_user])
    REFERENCES [dbo].[users] ([id])
    GO
    ALTER TABLE [dbo].[eclaims] CHECK CONSTRAINT [FK_eclaims_users]

The model is:

# coding: utf-8
class Eclaim < ActiveRecord::Base
end

As you can see there is auto-increment field named id_app.
When I try execute a query insert into eclaims (id_user, [property], title) values (1, 2, 'Alex') in MSSQL console everything goes perfect.

But when I try Eclaim.create(:id_user => 1, :property => 'inv', :change_date => Time.now )

I am getting such error TinyTds::Error: DEFAULT or NULL are not allowed as explicit identity values.: INSERT INTO [eclaims] ([id_app], [id_user], [property], [app_number], [patent_number], [native_number], [title], [applicants], [receive_date], [change_date]) VALUES (NULL, 1, N'inv', NULL, NULL, NULL, NULL, NULL, NULL, '2012-05-08 06:39:14.882')

Why ActiverRecord doesn't insert the auto-increment field id_app automatically?

Thanks in advance.

Upvotes: 1

Views: 1302

Answers (1)

Syed Aslam
Syed Aslam

Reputation: 8807

Rails is all conventions and it assumes 'id' column to be the primary key. However, since you chose to set 'id_app' to be your primary key of the table, you should tell that to Rails as well.

Use set_primary_key(value = nil, &block) to set 'id_app' as the primary key and it should work.

Upvotes: 1

Related Questions