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 

如何防止項目檢查自身的唯一約束?也就是說,如果數據庫中只有一個條目,那麼如果我們編輯該條目,則永遠不應拋出唯一約束。

回答

0

變化

@user_notification = UserNotification.new(user_notification_params) 

# I assume that you have id in your params 
@user_notification = UserNotification.find(params[:id]) 
@user_notification.assign_attributes(user_notification_params) 

當你正在做UserNotification.new(user_notification_params),然後試圖.save您的記錄,Rails使一個INSERT,這就是爲什麼你所得到的唯一性驗證錯誤。

當您致電assign_attributes時,您的現有模型將被填入新值而不保存。然後,您將其更改爲usercurrent_user並調用保存,它將向數據庫發送UPDATE查詢。

當然UserNotificationid應該是一個單獨的參數。它不應該包含在user_notification_params中。您只需要它在數據庫中查找所需的記錄。