ActiveRecord的:是否存在其他人创造更新记录? [英] ActiveRecord: Update a record if exists else create?
本文介绍了ActiveRecord的:是否存在其他人创造更新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图执行一个创建,如果不存在的Active Record其他更新的记录。
Trying to implement an create if not exists else update record in Active Record.
目前使用:
@student = Student.where(:user_id => current_user.id).first
if @student
Student.destroy_all(:user_id => current_user.id)
end
Student = Student.new(:user_id => current_user.id, :department => 1
)
Student.save!
会是什么,如果它存在,否则创建更新记录的正确方法是什么?
What would be the correct way of updating the record if it exists or else create it?
推荐答案
您可能会寻找 first_or_create
或类似的东西:
You may be looking for first_or_create
or something similar:
的http://guides.rubyonrails.org/v3.2.17/active_record_querying.html#first_or_create
这篇关于ActiveRecord的:是否存在其他人创造更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文