Search code examples
ruby-on-railsmodel-view-controlleractiverecordconsole

database record delete User.find_by_id().address.destroy


I am trying to delete the address result from here. I can add new address by doing this but I can't delete it

 $User.find_by_id(19).update(address: "canada")

I tried this but it is not working

 $User.find_by_id(19).destroy(address: "canada")

The output of

$User.find_by_id(19).destroy(address: "canada")
  User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 19]]
Traceback (most recent call last):
       10: from bin/rails:4:in `<main>'
        9: from bin/rails:4:in `require'
        8: from /app/vendor/bundle/ruby/2.6.0/gems/railties-4.2.11.1/lib/rails/commands.rb:17:in `<top (required)>'
        7: from /app/vendor/bundle/ruby/2.6.0/gems/railties-4.2.11.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        6: from /app/vendor/bundle/ruby/2.6.0/gems/railties-4.2.11.1/lib/rails/commands/commands_tasks.rb:68:in `console'
        5: from /app/vendor/bundle/ruby/2.6.0/gems/railties-4.2.11.1/lib/rails/commands/console.rb:9:in `start'
        4: from /app/vendor/bundle/ruby/2.6.0/gems/railties-4.2.11.1/lib/rails/commands/console.rb:110:in `start'
        3: from (irb):2
        2: from (irb):2:in `rescue in irb_binding'
        1: from /app/vendor/bundle/ruby/2.6.0/gems/activerecord-4.2.11.1/lib/active_record/transactions.rb:280:in `destroy'
ArgumentError (wrong number of arguments (given 1, expected 0))

Solution

  • I think you are trying to update the address field value from Canada to nil. If that's the case, what you are looking for is update, not destroy:

    User.find(19).update(address: nil)