Search code examples
ruby-on-railsrubyupdate-attributesupdate-attribute

Updating an attribute in Rails controller


I'm trying to update the shop_id of a user when they click an add button.

The controller method called is this:

def update_shop
  @user = User.find(params[:id])
  @shop = Shop.find(params[:shop_id])
  @user.update_attribute(:shop_id, params[:shop_id])
  flash[:success] = "Added Shop!"
  redirect_to @shop
end

The server when the button is clicked reads:

Started POST "/updateshop?id=3&shop_id=1" for ::1 at 2015-08-31 05:50:52 -0500
Processing by UsersController#update_shop as HTML
  Parameters: {"authenticity_token"=>"jRozldw1u3TrWhaL6CeJyw4Tm5V5S/IFEQQulRkuV1Ot85kmPOsMa2jH2L6m8EFDpy7Ygc9SMBvPLJCuosHXUg==", "id"=>"3", "shop_id"=>"1"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 3]]
  Shop Load (0.1ms)  SELECT  "shops".* FROM "shops" WHERE "shops"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  UPDATE "users" SET "shop_id" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["shop_id", 1], ["updated_at", "2015-08-31 10:50:52.089826"], ["id", 3]]
   (5.8ms)  commit transaction

But it doesn't actually update User.shop_id And sometimes it doesn't have the update line, and reads:

Started POST "/updateshop?id=3&shop_id=1" for ::1 at 2015-08-31 05:56:54 -0500
Processing by UsersController#update_shop as HTML
  Parameters: {"authenticity_token"=>"D1ODlfDnhJmQ9NUfh+GL2JE747nJC2t4eqOziRGNCaUvuikmEDkzhhNpGyrJNkNQOAagrX8SqWakiw2yqmKJpA==", "id"=>"3", "shop_id"=>"1"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 3]]
  Shop Load (0.1ms)  SELECT  "shops".* FROM "shops" WHERE "shops"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction

The parameters are passed correctly and I think update_attribute is correct, what's going wrong?


Solution

  • The value is already assigned, this is why it's not updated. I mean, there is no actual changes, this is why no UPDATE statements were issued.