首页 > 解决方案 > 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]]

标签: ruby-on-rails

解决方案


我和这个一起去了:

Account.update(current_user.account.id, post_id: nil)

让我知道另一种解决方案是否会更好。


推荐阅读