[RUBY] Data is not registered in Rails.

background </ font>

When saving data using ActiveRecord, there are times when the data is not saved. It's often slippery during validation, so keep it organized.

environment </ font>

item Contents
OS.Catalina v10.15.4
Ruby v2.5.1
Ruby On Rails v5.2.4.3

Contents </ font>

I don't have many opportunities, but when there is a service that creates an initial user, for example.

app/lib/make_default_data_service.rb


1    default_user = User.new
2    default_user.update_attributes(
3      id: 1,
4      password: 1111,
5      name: 'Unregistered user',
6      email: '[email protected]'
    )

When I run the service, no data is saved. When I investigate ...

  User Exists (32.4ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY '[email protected]' LIMIT 1
  ↳ app/lib/make_default_data_service.rb:15
   (0.5ms)  ROLLBACK

I was investigating up to the DB, mistakenly saying "Does user data already exist?" The second line of the above source has been modified.

(* After repair) app/lib/make_default_data_service.rb


1    default_user = User.new
2    default_user.update_attributes!(
3      id: 1,
4      password: 1111,
5      name: 'Unregistered user',
6      email: '[email protected]'
    )

Then. image.png

It seems that it violated the password character number convention. It's easier to understand. It's ok to replace it with the save → save! Method. Deployment is a bad pattern, but ... that's all.

Recommended Posts