尝试在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!
如果记录存在,则更新它的正确方法是什么?否则创建它?
find_or_initialize_by
和update_attributes!
的结合可以完成这个任务。 - fguillenupdate_attributes!
方法返回的是一个布尔值而不是实际记录。您可以使用Student.find_or_initialize_by(...).tap { |e| e.update!(...) }
来更新记录。 - eladoUser.where(email: email).find_or_initialize_by(password: password)
会给你一个错误columns users.password does not exist
(假设你明智地不将明文密码存储在数据库中)。 - PJSCopeland.update_attributes
更改为.update
。这是惯用的方法,源代码显示它与.update_attributes!
相同(它只会分配属性并调用.save
...请查看https://apidock.com/rails/ActiveRecord/Persistence/update和https://apidock.com/rails/v3.2.3/ActiveRecord/Persistence/update_attributes)。 - sandre89find_or_initialize_by
可能不会触发任何验证。 - hugholousk