Theopap
Theopap

Reputation: 755

Rails: update an attribute to nil

I have an integer column post_id that has a value in the db and I would like to update it to nil from the controller.

I have tried the following but unfortunately the value remains the same and does not change to nil:

current_user.account.update(post_id: nil)
current_user.account.update(post_id: 0)

Any ideas on how I can update the post id to nil?

Update 1

Account table

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

the link to:

<%= link_to "Remove post from user", remove_post_path, data: { confirm: "Are you sure?" } %>

the route:

get "user/remove_post", to: "accounts#remove_post", :as => : remove_post

the controller method:

def remove_post
  current_user.account.update_attributes(post_id: nil)
end

What i get in the console:

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]]

Upvotes: 1

Views: 5780

Answers (3)

Theopap
Theopap

Reputation: 755

I went with this:

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

Let me know if another solution might be better.

Upvotes: 1

Arslan
Arslan

Reputation: 21

Maybe Try

ac = Account.first
ac.post_id = nil
ac.save(validate: false)

Upvotes: 1

barmic
barmic

Reputation: 1097

It seems that you have the relation between account and post. By default, Rails validates weather the relation exists. You can change this by adding optional: true to your model:

class Account < ApplicationRecord
  belongs_to :post, optional: true
end

After this, you can change successfully value of this column to nil.

Upvotes: 0

Related Questions