You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails中调用destroy清除用户Address属性值失败报错求助

如何清除用户的address属性值?

我可以通过以下代码设置用户的address属性:

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

但尝试用destroy方法清除该值时失败了:

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

执行后得到报错:

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

错误原因

destroy方法是用来删除整个数据库记录的,它不需要传入任何参数。你传入address: "canada"属于传参错误,所以触发了ArgumentError。

正确的清除方式

要清除单个属性值,应该继续使用update方法,把address设为nil或者空字符串(根据业务需求选择):

  • 设为nil(数据库中存储为NULL):
$User.find_by_id(19).update(address: nil)
  • 设为空字符串:
$User.find_by_id(19).update(address: "")

如果需要更高效的批量操作(注意此方式不会触发模型回调),可以使用update_all:

$User.where(id: 19).update_all(address: nil)

内容的提问来源于stack exchange,提问作者Nour Abu Khajil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:45:02