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

后端 未结 2 1152
心在旅途
心在旅途 2021-01-01 13:13

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

相关标签:
2条回答
  • 2021-01-01 13:28

    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

    0 讨论(0)
  • 2021-01-01 13:35
    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 讨论(0)
提交回复
热议问题