ruby-on-rails - Rails:将属性更新为 nil
问题描述
我有一个整数列post_id
,它在 db 中有一个值,我想从控制器将它更新为 nil。
我尝试了以下方法,但不幸的是该值保持不变并且不会更改为 nil:
current_user.account.update(post_id: nil)
current_user.account.update(post_id: 0)
关于如何将帖子 ID 更新为 nil 的任何想法?
更新 1
账户表
create_table "accounts", force: :cascade do |t|
t.string "name"
t.string "street"
t.string "city"
t.string "state"
t.string "postal_code"
t.string "country"
t.integer "post_id", default: 0
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
链接到:
<%= link_to "Remove post from user", remove_post_path, data: { confirm: "Are you sure?" } %>
路线:
get "user/remove_post", to: "accounts#remove_post", :as => : remove_post
控制器方法:
def remove_post
current_user.account.update_attributes(post_id: nil)
end
我在控制台中得到什么:
Account Update (0.6ms) UPDATE "accounts" SET "post_id" = $1, "updated_at" = $2 WHERE "accounts"."id" = $3 [["post_id", 96], ["updated_at", "2019-02-27 10:43:53.432402"], ["id", 49]]
解决方案
我和这个一起去了:
Account.update(current_user.account.id, post_id: nil)
让我知道另一种解决方案是否会更好。
推荐阅读
- java - Android 如何使用共享首选项检查用户登录或注销
- haskell - 无法将类型与 Maybe b0 匹配
- unit-testing - 如何模拟打开不存在的文件
- excel - 在表格底部插入新行并删除顶行的问题
- python - 如何删除熊猫中多个括号之间的单词?
- java - 如何在 Visual Studio Code (v 1.27.2) 中设置 java 类路径?
- jquery - 一页中有多个表单,数据应存储在不同的表中
- python - 如何使用 imdb 中的 imdbpy 检索特定电影 ID 的情节关键字
- android - NotificationCompat.Builder() 不接受 Channel Id 作为参数
- javascript - 如何将变量从一个函数调用到另一个函数