ActiveRecord: Update a record if exists else create?

后端 未结 7 1673
北荒
北荒 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 20:05

    In Rails 5

    Student.
      find_or_initialize_by(:user_id => current_user.id).
      update(:department => 1)
    

    (with all credit taken from @Zorayr answer).

    0 讨论(0)
提交回复
热议问题