2010-06-04 29 views
17

我有一個沒有ID列的表。當我嘗試使用ActiveRecord從中刪除時,生成的SQL爲DELETE FROM table_name WHERE ID=NULL,這顯然不起作用。有沒有辦法使用ActiveRecord從表中刪除,或者至少用佔位符運行原始SQL刪除查詢(所以它不容易受SQL注入攻擊)?如何銷燬沒有ID列的記錄在ruby ActiveRecord中?

回答

24

您是否嘗試過使用ActiveRecord的delete_all方法?下面是我的一個沙箱的摘錄:

>> customer = Customer.new(:login => 'foo') 
=> #<Customer id: nil, status: 0, name: nil, login: "foo", password: nil, salt: nil, api_key: nil, address: nil, town: nil, state: nil, country: "USA", zipcode: nil, balance: #<BigDecimal:1032669b0,'0.0',9(18)>, discount: 0, last_four_cc: nil, auto_renew: false, contact_name: nil, contact_email: nil, domain: "anon.limelock.com", created_at: nil, updated_at: nil> 
>> customer.save 
=> true 
>> Customer.all.count 
=> 4 
>> Customer.delete_all(:login => 'foo') 
=> 1 
>> Customer.all.count 
=> 3 

生成的SQL是DELETE FROM `customers` WHERE (`customers`.`login` = 'foo')

退房的documentation

+0

這是要走的路。我正要回答這個問題。 – 2010-06-05 14:59:15

+0

這不適用於所有情況。我有一個模型遊戲和一個模型AppVersion。遊戲has_many:app_versions。 'Game.first.app_versions.delete_all'產生'DELETE FROM'app_versions'WHERE'app_versions'。''= NULL',這是一個錯誤。 – 2012-02-14 12:53:19

+0

當你在一個關係上使用它時,Rails4.2說在'.delete_all'方法中,只有兩個選項可以傳遞:':nullify',它在foreing_keys和':delete_all'上設置null,它實際上刪除了這些對象。默認值是':nullify'。 – mariowise 2015-05-26 12:43:01

8
ActiveRecord::Base.connection.execute('DELETE FROM table_name WHERE ...') 

我認爲你需要有一個ActiveRecord的唯一id列來正常工作,但我不是100%確定的。

+0

AFAIK這不符合佔位符的工作。 – Johnny 2010-06-04 22:58:44

+0

'sanitize_sql_array'將解決佔位符問題。 – x1a4 2010-06-05 02:13:29

相關問題