开发者

how can I destroy a record without an ID column in ruby ActiveRecord?

开发者 https://www.devze.com 2023-01-02 21:26 出处:网络
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 delet

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 开发者_StackOverflowplaceholders (so it's not vulnerable to SQL injection)?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消