我的Rails應用程序有些奇怪的事情發生。每次用戶訪問我之前創建的唯一網址時,都會調用控制器操作並將記錄保存到表中。Rails:同時創建的重複記錄
不幸的是,有時會創建兩個相同的記錄而不是一個。我添加了「validates_uniqueness_of」,但它不起作用。
我的控制器代碼:
class ShorturlController < ApplicationController
def show
@shorturl = ShortUrl.find_by_token(params[:id])
@card = Card.find(@shorturl.card_id)
@subscriber = BotUser.find_by_sender_id(params['u'])
@letter_campaign = Letter.find(@card.letter_id).campaign_name.downcase
if AnalyticClic.where(card_id: @card.id, short_url_id: @shorturl.id, bot_user_id: @subscriber.id).length != 0
@object = AnalyticClic.where(card_id: @card.id, short_url_id: @shorturl.id, bot_user_id: @subscriber.id)
@ccount = @object[0].clicks_count
@object.update(updated_at: Time.now, clicks_count: @ccount += 1)
else
AnalyticClic.create(card_id: @card.id, short_url_id: @shorturl.id, bot_user_id: @subscriber.id, clicks_count: "1".to_i)
end
@final_url = @card.cta_button_url
redirect_to @final_url, :status => 301
end
end
和模型:
class AnalyticClic < ApplicationRecord
validates_uniqueness_of :bot_user_id, scope: :card_id
end
任何想法,爲什麼有時我還重複記錄? if應該防止以及validates_uniqueness_of。
你應該把驗證檢查在數據庫級別上,不只是在車型。請參閱[do-rails-need-database-level-constraints](https://stackoverflow.com/questions/2589509/does-rails-need-database-level-constraints) –