Validate scoped uniqueness in polymorphic association models

后端 未结 2 719
失恋的感觉
失恋的感觉 2021-02-19 07:36

Right, so I have a polymorphic association that allows for different object types to be favorited. So a person can favorite a product, or a person, or whatever. What I want to d

相关标签:
2条回答
  • 2021-02-19 08:03

    If you closely observe you can find that uniqueness validation just work fine :)

    validates :user_id, :uniqueness => { :scope => [:favoritable_type, :favoritable_id] }
    

    Look at the data image you added. inside image you can find out that second record is not having favouritable whereas first have which is different hence 2 records are uniq and its not issue with uniqueness but its your logical gap.

    If you strictly wanted to avoid second entry then keep favouritable as mandatory field

    validates :favoritable_type, :favoritable_id, :presence => true
    
    0 讨论(0)
  • 2021-02-19 08:21
    class Favorite < ActiveRecord::Base
    
      belongs_to :user
      belongs_to :favoritable, polymorphic: true
    
      validates :user_id, :favoritable_id, presence: true,
        numericality: { only_integer: true }
    
      validates :favoritable_type, presence: true,
        inclusion: { 
          in: %w(FirstModelName SecondModelName),
          message: "%{value} is not a valid" 
        }
    
      validates :user_id, uniqueness: { scope: [ :favoritable_type, :favoritable_id ] }
    end
    
    0 讨论(0)
提交回复
热议问题