ActiveRecord: Update a record if exists else create?

后端 未结 7 1671
北荒
北荒 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:45

    In Rails 4

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

提交回复
热议问题