Validate scoped uniqueness in polymorphic association models

后端 未结 2 721
失恋的感觉
失恋的感觉 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: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
    

提交回复
热议问题