2009-01-23 44 views
2

(這個問題最初是在幾個月前發佈在另一個論壇上,沒有得到任何答案......在這些時候沒有SO!)Ruby on Rails和MSSQL Server:嘗試插入newid()默認值的行

我在RoR的第一步。我借鑑了其中一本關於Ruby和Ruby On Rails的書。示例在MySQL上正確運行,因此我決定將它們重寫爲MS-SQL作爲一個良好的練習(並且MS-SQL是我們的標準數據庫)..並且它變成了一個噩夢:

我有這張表與2個字段

Tbl_People 
---------- 
id_People  primary key, newid() default value, 
namePeople  string 

我有一個ODBC連接到數據庫。我可以列出記錄,但是......我無法在表格中插入任何內容。由紅寶石產生的INSERT串如下:

INSERT INTO Tbl_People (id_People, namePeople) VALUES('newid','GRONDIER, Philippe') 

並且將被拒絕,因爲字符串「newid的」不能在uniqueindentifier /主鍵字段id_People插入。從邏輯上講,返回的錯誤是:

DBI::DatabaseError: 37000 (8169) [Microsoft] [ODBC SQL Server Driver][SQL Server]Conversion failed when converting from a character string to uniqueidentifier 

這似乎是如此顯然是一個重要和基本的問題,我覺得我錯過了一些東西通常用粗體每個RoR的培訓文件,如「不要試圖通過回報率的INSERT ','uniqueIdentifier是RoR的中文',或'RoR不能與MS SQL Server一起使用'...

任何想法?

回答

1

我不是一個紅寶石男人,所以請記住這一點。其中大部分只是在MySQL-> MSSQL翻譯IMO中丟失了。

因此,您的ID是「uniqueidentifier」類型。其中一件事情應該發生:

a)你應該傳入NEWID()作爲第一個參數。不是字符串'newid',但函數NEWID()

b)不傳入第一個參數。由於有一個默認值,只需插入NamePeople列。

根據使用情況,如果處理分佈式數據,我只會使用uniqueidentifier主鍵,而對於大多數關鍵引用,我會堅持使用舊的INT IDENTITY列。

+0

的INSERT字符串自動生成的紅寶石,而不是我。 RUBY生成字符串的方式顯然不正確。 – 2009-01-23 10:01:50

1

看看這篇文章,不同的數據庫類型,但基本上相同的問題,如何隱藏來自RoR的默認字段,因此無法生成無效插入。

EDIT @ wayne-conrad指出舊鏈接已經死亡。我相信內容是在這裏找到的, http://inodes.org/2008/01/11/rails-activerecord-mysql-guids-and-the-rename_column-bug/

下面的關鍵摘錄。

頁面的評論部分還引用旨在解決這個問題的一個項目 https://github.com/cch1/uuid_primary_key/tree/master(鏈接不要辜負我!)

# HACK (JF) - This is too evil to even blog about 
    # When we use guid as a primary key we usually rename the original 'id' 
    # field to 'integer_id'. We need to hide this from rails so it doesn't 
    # mess with it. WARNING: This means once you use usesguid anywhere you can 
    # never access a column in any table anywhere called 'integer_id' 

class ActiveRecord::Base 
    private 
    alias :original_attributes_with_quotes :attributes_with_quotes 

    def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true) 
     quoted = original_attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true) 
     quoted.delete('integer_id') 
     quoted 
    end 
end 
+0

謝謝。在這個博客中暴露的問題是完全不同的,但仍然是一般的興趣。讀完這個之後,我想建立一個函數來在客戶端生成uniqueId值 – 2009-01-23 02:25:20