Validate scoped uniqueness in polymorphic association models

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

提交回复
热议问题