0
我使用Rails 5.我有這種模式具有唯一約束如何防止Rails檢查正在編輯/更新的對象的唯一約束?
class UserNotification < ActiveRecord::Base
belongs_to :user
belongs_to :crypto_currency
validates_uniqueness_of :buy, scope: [:user_id, :crypto_currency_id]
end
我用這個方法來處理更新模型
def update
@user_notification = UserNotification.new(user_notification_params)
@user_notification.user = current_user
respond_to do |format|
if @user_notification.save
format.html { redirect_to user_notifications_path, notice: 'Updated successfully.' }
else
format.html { render action: "new" }
@crypto_currencies = CryptoCurrency.where(id: CryptoIndexCurrency.all.pluck(:crypto_currency_id).uniq).order(:name)
puts "full messages: #{@user_notification.errors.full_messages}"
end
end
end
即使有在只有一個條目我數據庫,當我在現有的條目上調用上述方法時,我得到我的模型中的錯誤,抱怨違反了唯一約束(else分支被調用)...
Buy has already been taken
如何防止項目檢查自身的唯一約束?也就是說,如果數據庫中只有一個條目,那麼如果我們編輯該條目,則永遠不應拋出唯一約束。