1

我正在使用:
Rails 3.0.9
Activerecord-sqlserver-adapter 3.0.15
TinyTds
MSSQL 2005

我有下表:

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]

型号为:

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

如您所见,有一个名为 id_app 的自动增量字段。
当我尝试在 MSSQL 控制台中执行查询insert into eclaims (id_user, [property], title) values (1, 2, 'Alex')时,一切都很完美。

但是当我尝试Eclaim.create(:id_user => 1, :property => 'inv', :change_date => Time.now )

我收到这样的错误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')

为什么 ActiverRecord 不会自动插入自增字段id_app

提前致谢。

4

1 回答 1

1

Rails 是所有约定,它假定 'id' 列是主键。但是,由于您选择将 'id_app' 设置为表的主键,因此您也应该将其告知 Rails。

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

于 2012-05-08T08:02:39.017 回答