我正在使用postgresql和rails 4.2进行应用程序开发。
问题在于:
当创建用户模型时,我需要在此期间创建与用户模型相关联的另外两个模型:profile model和user_behavior模型。为了保持记录的一致性,事务使用如下:
begin
@new_user = User.new
@new_user.transaction do
@new_user.update_attributes!(users_params)
@new_user.profile = Profile.create!(profiles_params)
@new_user.user_behavior = UserBehavior.create!
end
rescue ActiveRecord::RecordInvalid => exception
render_response_msg(4003, { message: exception.message })
rescue ArgumentError => exception
render_response_msg(4003, { message: "invalid parameters" })
end
@new_user
用户模型和个人资料模型都有一些验证
问题1。我使用实例变量 @new_user 将新创建的用户记录从事务范围中删除,我不确定这是执行此操作的通用方法,还有其他想法吗?
问题2。当用户params好时,它传递并创建用户记录,然后profile params无效,使整个事务回滚。然后我发现用户模型的id(轨道中模型的基本自动增量id)是不连续的。例如,如果由于profile params而失败两次,那么成功事务将创建id = 3的模型。我该如何解决这个问题?
答案 0 :(得分:0)
[编辑对问题1的回复是不可能的,因为无法返回本地变量,因为我在评论中指出我在原帖中错过了]
针对问题1: 我认为本文中提供的说明http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html 会有所帮助。因此,我会做如下的事情:
User.transaction do
new_user = User.new(user_params)
new_user.profile = Profile.create!(profile_params)
new_user.behavior = UserBehavior.create!
new_user.save!
end
响应问题2:正如mu is too short指出的那样,无关紧要,但是postgresql对数据库中的每个表使用一个序列表,通常命名为[YOUR_TABLE_NAME]_id_seq
,你必须改变值该表中的last_value列为了调整id序列,但是错误肯定会在保持唯一性方面造成很多问题,我当然会建议不要使用它。