Ruby on Rails:从guest用户转移到注册用户时,依赖对象被销毁

时间:2015-05-27 15:36:18

标签: ruby-on-rails ruby ruby-on-rails-4 devise

这是我的问题:

我正在使用Devise's guest_user,它包含一个logging_in方法,用于在登录时将guest_user参数传输给注册用户。所以在我的情况下,用户has_many periods, dependent: :destroy,所以这里是logging_in方法:

def logging_in
  guest_periods = guest_user.periods.all
  guest_periods.each do |p|
    p.user_id = current_user.id
    p.save!
  end

  current_user.latest_entry = guest_user.latest_entry
  current_user.is_in_zone = guest_user.is_in_zone
  current_user.save
end

但是,当guest_user登录时,他的句点会被销毁而不是被转移。这是日志:

Started GET "/" for ::1 at 2015-05-11 00:18:03 +0300
Processing by WelcomeController#index as HTML
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 24]]
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 23]]
  Period Load (0.3ms)  SELECT "periods".* FROM "periods" WHERE "periods"."user_id" = $1  [["user_id", 23]]
   (0.2ms)  BEGIN
  CACHE (0.0ms)  SELECT "periods".* FROM "periods" WHERE "periods"."user_id" = $1  [["user_id", 23]]
  SQL (0.8ms)  UPDATE "periods" SET "user_id" = $1, "updated_at" = $2 WHERE "periods"."id" = $3  [["user_id", 24], ["updated_at", "2015-05-10 21:18:03.863162"], ["id", 170]]
   (0.9ms)  COMMIT
   (0.2ms)  BEGIN
  SQL (2.1ms)  UPDATE "users" SET "is_in_zone" = $1, "latest_entry" = $2, "updated_at" = $3 WHERE "users"."id" = $4  [["is_in_zone", "t"], ["latest_entry", "2015-05-04"], ["updated_at", "2015-05-10 21:18:03.875572"], ["id", 24]]
   (15.8ms)  COMMIT
   (0.5ms)  BEGIN
  SQL (0.3ms)  DELETE FROM "periods" WHERE "periods"."id" = $1  [["id", 170]]
  SQL (0.7ms)  DELETE FROM "users" WHERE "users"."id" = $1  [["id", 23]]
   (1.2ms)  COMMIT

所以我们可以看到转移已经完成,但最后,无论如何都会破坏这些时期。它们不应该是,因为它们不再属于要被销毁的用户。

为什么会这样?

1 个答案:

答案 0 :(得分:2)

即使Period#user_id已更改,guest_user.periods仍会在内存中加载,并且在销毁来宾用户时会被销毁。如果你guest_user.reload,它的关联将清除,并且它可以安全地销毁。您还可以guest_user.periods(true)强制重新加载句点。

另一种选择是:

guest_user.periods.update_all(user_id: current_user.id)

这会执行单个查询来执行更新,如果有很多句点会很好,并且也不会加载guest_user.periods关联,所以它会在销毁期间加载新的并找到正确的空集。