如何防止Rails检查正在编辑/更新的对象的唯一约束?

问题描述:

我使用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 

如何防止项目检查自身的唯一约束?也就是说,如果数据库中只有一个条目,那么如果我们编辑该条目,则永远不应抛出唯一约束。

变化

@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中。您只需要它在数据库中查找所需的记录。