ruby-on-railsdestroy

Rails | how to use destroy_by?


I'm attempting to destroy some records as part of a transaction (there will only ever be a handful to delete at a time). As such, I'm making a call like the following:

MyModel.destroy_by(:foreign_id => "XXX")

Unfortunately this is producing some bad SQL and failing. Here's the output from attempting to execute it in the rails console:

[3] pry(main)> MyModel.destroy_by(:foreign_id => "XXX")
  MyModel Load (0.4ms)  SELECT "my_model".* FROM "my_model" WHERE "my_model"."foreign_id" = $1  [["foreign_id", "XXX"]]
  TRANSACTION (0.4ms)  BEGIN
  MyModel Destroy (0.7ms)  DELETE FROM "my_model" WHERE "my_model"."" IS NULL
  TRANSACTION (0.4ms)  ROLLBACK
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: ...TE FROM "my_model" WHERE "my_model"."" IS NULL
                                                             ^

from /home/rwilliams/.rvm/gems/ruby-2.7.6/gems/activerecord-6.1.7.2/lib/active_record/connection_adapters/postgresql_adapter.rb:672:in `exec_params'
Caused by PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: ...TE FROM "my_model" WHERE "my_model"."" IS NULL
                                                             ^

rails version = Rails 6.1.7.2

EDIT: There is expected to be more than one record with the specified foreign_id, and I want them all destroyed

EDIT 2: I have also attempted MyModel.where(...).destroy_all and get the same error

EDIT 3: The my_model table does not have an id column. This is most likely why the default destroy/delete operations are failing. So I'm looking into how to make it work.... This is a new table, so I do have the option of adding the id column back in if it is ultimately necessary to work with rails


Solution

  • Seems like the issue is trying to delete/destroy a record from a table with no ID column. More details https://discuss.rubyonrails.org/t/calling-destroy-on-a-model-that-has-no-id-column/51101

    An alternative is to use the composite_primary_key gem but I'd suggest adding an id to stick with the rails convention because I've seen issues with that gem in the past during upgrades.