1
由於某些原因,以下代碼會創建重複項。它並不總是發生。如果我刷新足夠多的時間就會停止發生。奇怪的是,它創建的「重複」甚至不匹配我的用戶ID!這是在開發中。用戶表甚至沒有id = 1的用戶。rails find_or_create_by創建重複項
@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]]