我正在使用:
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 ?
提前致谢。
答案 0 :(得分:1)
Rails是所有约定,它假定'id'列为主键。但是,由于您选择将'id_app'设置为表的主键,因此您应该将其告知Rails。
使用set_primary_key(value = nil, &block)将'id_app'设置为主键,它应该可以正常工作。