在使用Rails的ActiveRecord對(duì)數(shù)據(jù)庫(kù)進(jìn)行更新操作時(shí),如果使用update(id,:field =>value) 方法更新數(shù)據(jù),則此時(shí)rails并不是執(zhí)行以下過(guò)程:
1. Update table set field = value where id = id 而是實(shí)際執(zhí)行了 2. Update table set field = value , field2 = value2 … where id = id 這意味著當(dāng)數(shù)據(jù)庫(kù)中這張表?yè)碛?/span>50個(gè)字段的時(shí)候,Rails就分別更新了50個(gè)字段,只是將程序指定的field替換成了指定的value,其它沒(méi)有指定的field一般不是我們所期望的執(zhí)行更新的。 解決這個(gè)問(wèn)題的方法是使用ActiveRecord::Base的connection.execute方法,這個(gè)方法可以直接寫(xiě)更新數(shù)據(jù)庫(kù)的sql語(yǔ)句,當(dāng)然也可以執(zhí)行SQL Server存儲(chǔ)過(guò)程。使用以下語(yǔ)句就可以執(zhí)行1中的數(shù)據(jù)庫(kù)操作: Connection.execute(“update table set field = value where id = id”)