ActiveRecord: Update a record if exists else create?

后端 未结 7 1734
北荒
北荒 2020-12-30 19:04

Trying to implement an create if not exists else update record in Active Record.

Currently using:

@student = Student.where(:user_id          


        
7条回答
  •  生来不讨喜
    2020-12-30 19:48

    Unfortunately I think the cleanest way to do this is:

    Student.where(user_id: id).first_or_create(age: 16).update_attribute(:age, 16)
    

提交回复
热议问题