Rails: dependent: :destroy 即使在重新分配后也会删除记录

Rails: dependent: :destroy deletes record even after reassignment

我有一个 Rails 5 应用程序,用户可以在其中注册为访客 User 来试用我的服务。每个 User(和来宾用户)可以有很多 App。关系如下所示:

# User.rb
has_many :apps, dependent: :destroy

# App.rb
belongs_to :user

当来宾用户决定注册我想要的服务时:

我遇到的问题是,即使我将 app.user 重新分配给新的 current_user(我使用设备 gem),在删除老访客用户。

在我的 class Users::RegistrationsController < Devise::RegistrationsController 中,我像这样覆盖 create 操作(相关部分):

# POST /resource
def create
  user_params = params[:user]
  new_user_from_guest = guest_user
  build_resource(sign_up_params)
  resource.save
  yield resource if block_given?
  if resource.persisted?
    if resource.active_for_authentication?
      set_flash_message :notice, :signed_up if is_flashing_format?
      sign_up(resource_name, resource)

      # Reassigns the app
      reasign_app_for_user(new_user_from_guest)

      Mailer.deliver_welcome_message(current_user).deliver_later!
      respond_with resource, location: after_sign_up_path_for(resource)

      # delete the guest user (this also deletes the app)
      delete_guest_user!
    else
      [...]
    end
  else
    [...]
  end
end

# ... my private methods for deleting the current user and reassigning the app's owner.
def reasign_app_for_user(user)
  user.apps.each do |app|
    app.user = current_user
    app.save!
  end
end

# ... this method deletes the app, even if it is called after the reassign method.
def delete_guest_user!
  guest_user(with_retry = false).try(:destroy)
  session[:guest_user_id] = nil
end

关于为什么会发生这种情况或我做错了什么有什么想法吗?

更新

这是我的 user_params 变量提交后的样子:

<ActionController::Parameters {"name"=>"Test user", "email"=>"test@example.com", "password"=>"testing"} permitted: false>

这就是 sign_up_params 的样子:

{"email"=>"test@example.com", "password"=>"testing", "name"=>"Test"}

我会考虑在将应用分配给新用户之前复制这些应用。这样,就不会混淆它是否是同一个应用程序。

guest.apps.each do |app|
  current_user.apps << app.dup
end

就是这样。铲子操作员确保将新的重复应用程序保存到 current_user 对象。

或者更简单更紧凑:

current_user.apps = guest.apps.map(&:dup)
current_user.save