views:

40

answers:

2

hi,

I have a table without an ID column. When I try to delete from it using ActiveRecord the generated SQL is DELETE FROM table_name WHERE ID=NULL, which obviously doesn't work. Is there any way to delete from the table using ActiveRecord, or at least run a raw SQL delete query with placeholders (so it's not vulnerable to SQL injection)?

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

I think you need to have a unique id column for ActiveRecord to function right, but I'm not 100% sure.

Zepplock
AFAIK this doesn't work with placeholders.
Johnny
`sanitize_sql_array` will solve the placeholder issue.
x1a4
+2  A: 

Have you tried using ActiveRecord's delete_all method? Here's an excerpt in a sandbox of mine:

>> 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

The generated SQL is DELETE FROM `customers` WHERE (`customers`.`login` = 'foo')

Check out the documentation

This is the way to go. I was going to answer this.
François Beausoleil