How do you validate uniqueness of a pair of ids in Ruby on Rails?

前端 未结 6 2056
梦如初夏
梦如初夏 2020-12-04 17:31

Suppose the following DB migration in Ruby:

    create_table :question_votes do |t|
      t.integer :user_id
      t.integer :question_id
      t.integer :vote

          


        
6条回答
  •  悲哀的现实
    2020-12-04 18:02

    When you are creating a new record, that doesn't work because the id of your parent model doesn't exist still at moment of validations.

    This should to work for you.

    class B < ActiveRecord::Base
      has_many :ab
      has_many :a, :through => :ab
    end
    
    class AB < ActiveRecord::Base
      belongs_to :b
      belongs_to :a
    end
    
    class A < ActiveRecord::Base
      has_many :ab
      has_many :b, :through => :ab
    
      after_validation :validate_uniqueness_b
    
      private
      def validate_uniqueness_b
        b_ids = ab.map(&:b_id)
        unless b_ids.uniq.length.eql? b_ids.length
          errors.add(:db, message: "no repeat b's")
        end
      end
    end
    

    In the above code I get all b_id of collection of parameters, then compare if the length between the unique values and obtained b_id are equals.
    If are equals means that there are not repeat b_id.

    Note: don't forget to add unique in your database's columns.

提交回复
热议问题