composite-primary-keys / composite_primary_keys

Composite Primary Keys support for Active Record
1.03k stars 350 forks source link

Uniqueness validation doesn't work #517

Closed varvaray closed 3 years ago

varvaray commented 4 years ago

Gem version - composite_primary_keys (8.1.3) Rails version - rails (4.2.11)

I have a model with composite primary key - self.primary_key = %i(code partnerid) And i have a uniqueness validation on code looking like that -

validates :code, presence: true, length: { maximum: 3, minimum: 3 },
                uniqueness: { scope: :partnerid, case_sensitive: false }, format: { with: /\A[A-Z]*\z/, message: 'Only capital letters allowed' }

It works nicely on create -

SELECT  1 AS one FROM `config`.`multipliers` WHERE (`config`.`multipliers`.`code` = 'RUB' AND `config`.`multipliers`.`partnerid` = 220) LIMIT 1

But on update the exists request to database looks like that -

SELECT  1 AS one FROM `config`.`multipliers` WHERE (`config`.`multipliers`.`code` = 'RUB' AND (`config`.`multipliers`.`code` != 'RUB' OR `config`.`multipliers`.`partnerid` != 0) AND `config`.`multipliers`.`partnerid` = 0) LIMIT 1

Which results in passing it through and then getting ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'LOL-0' for key 'PRIMARY': UPDATE

varvaray commented 4 years ago

I wrote a workaround -

    def uniqueness
      errors.add(:base, :already_used) if Multiplier.exists?(code: code, partnerid: brand_id)
    end

with validate :uniqueness for the model, which seems to work, but would be nice to have uniqueness support out of the box.

cfis commented 4 years ago

Thanks for the report - that does seem like a bug.

cfis commented 3 years ago

Took a look at this at it works as expected on the latest version (CPK 12.) on Rails 6.0..

So going to close this. CPK 8.* is no longer supported, I'd recommend upgrading if at all possible.