如何在ruby ActiveRecord中销毁没有ID列的记录?

时间:2010-06-04 22:32:39

标签: ruby-on-rails ruby activerecord

我有一张没有ID列的表。当我尝试使用ActiveRecord从中删除时,生成的SQL为DELETE FROM table_name WHERE ID=NULL,这显然不起作用。有没有办法使用ActiveRecord从表中删除,或者至少使用占位符运行原始SQL删除查询(因此它不容易受到SQL注入的影响)?

2 个答案:

答案 0 :(得分:25)

您是否尝试过使用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

答案 1 :(得分:10)

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

我认为你需要为ActiveRecord提供一个唯一的id列才能正常运行,但我不是百分百肯定。