出于某种原因,以下代码会创建重复项。它并不总是发生。如果我刷新足够多的时间,它就会停止发生。奇怪的是,它创建的“重复”甚至与我的用户 ID 不匹配!这是在开发中。User 表甚至没有 id = 1 的用户。
@food.page_views.find_or_create_by_user_id(current_user)
这是我的 current_user 方法。
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
session[:user_id] = nil
end
helper_method :current_user
end
从控制台:
PageView Load (0.4ms) SELECT "page_views".* FROM "page_views" WHERE "page_views"."food_id" = 2 AND "page_views"."user_id" = 3 LIMIT 1
(4.0ms) BEGIN
SQL (0.6ms) INSERT INTO "page_views" ("created_at", "food_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Tue, 25 Sep 2012 01:36:43 UTC +00:00], ["food_id", 2], ["updated_at", Tue, 25 Sep 2012 01:36:43 UTC +00:00], ["user_id", 1]]