bo-oz
bo-oz

Reputation: 2872

Uniqueness validation of record in polymorphic model in Rails

So I have this big headache trying to solve a bug that only happens sometimes... I have the following model for allowing a user to like something:

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :likeable, polymorphic: true
  validates :user, uniqueness: {scope: :likeable}
end

This is a set up to allow a user to like multiple other models and has a validation that prevents a user to like the same thing multiple times.

The thing I discovered after debugging is that the SELECT query run by rails seems to check only for the uniqueness of likeable_id (and not likeable_type):

SELECT  1 AS one FROM "likes" WHERE ("likes"."user_id" = 1 AND "likes"."likeable_id" = 4) LIMIT 1

Logically, when a user had already liked a comment with id is 4, he couldn't like any other thing with the same ID.

Any ideas on how to solve this?

Upvotes: 2

Views: 902

Answers (1)

Kh Ammad
Kh Ammad

Reputation: 1085

According to the docs, you can define uniqueness validation on both type and id: http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of#893-Does-not-work-with-polymorphic-relations

class Like < ActiveRecord::Base
   belongs_to :user
   belongs_to :likeable, polymorphic: true
   validates :user, uniqueness: {scope: [:likeable_id, :likeable_type]}
 end

Upvotes: 3

Related Questions