Sergey Chechaev
Sergey Chechaev

Reputation: 570

first_or_initialize bug or what happened

I try to insert record but Active Record do same magick that i don't understand !?!?!? My test code:

  UserToken.where(:user_id=>2).first_or_initialize.tap  do |user|
     user.token   = 'token',
     user.type_id = 0,  
     user.user_id = 2 
     user.save!
  end

Result:

 UserToken Load (56.9ms)  SELECT `user_tokens`.* FROM `user_tokens` WHERE `user_tokens`.`user_id` = 2 LIMIT 1
   (56.4ms)  BEGIN
   (56.4ms)  UPDATE `user_tokens` SET `type_id` = 0, `token` = '---\n- token\n- 0\n- 2\n', `updated_at` = '2013-06-27 20:19:22' WHERE `user_tokens`.`id` = 19
   (56.3ms)  COMMIT
=> #<UserToken id: 19, user_id: 2, token: ["token", 0, 2], type_id: 0, created_at: "2013-06-27 20:14:11", updated_at: "2013-06-27 20:19:22">

Why update token token = '---\n- token\n- 0\n- 2\n', token: ["token", 0, 2] i just try to record 'token' not array ?!?!?!?

Upvotes: 1

Views: 624

Answers (1)

Matthew Graves
Matthew Graves

Reputation: 3284

you shouldn't have those commas there

  UserToken.where(:user_id=>2).first_or_initialize.tap  do |user|
     user.token   = 'token'
     user.type_id = 0
     user.user_id = 2 
     user.save!
  end

or with semicolon line enders:

  UserToken.where(:user_id=>2).first_or_initialize.tap  do |user|
     user.token   = 'token';
     user.type_id = 0;
     user.user_id = 2;
     user.save!;
  end

The way you have it you're passing the other two assignments to user.token. What you did ends up like this because ruby expression always have a return value and variables always return themselves:

user.token = 'token', 0, 2

Upvotes: 2

Related Questions