diff --git a/README.md b/README.md index 835c183..fb55242 100644 --- a/README.md +++ b/README.md @@ -347,19 +347,6 @@ rating: Now the rates will be written on `reviews` table over `rating_rates` and calculation will be on `review_ratings` over `rating_ratings`. You can change one table o both of them. - -## Validation - -It is recommended that you add a validation to ensure that the author do not vote multiple times on the same resource and its scope. -This validation is not inside the gem since you could want make your own custom validation. - -```ruby -validates :author_id, uniqueness: { - case_sensitive: false, - scope: %i[author_type resource_id resource_type scopeable_id scopeable_type] -} -``` - ## Love it! Via [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=X8HEP2878NDEG&item_name=rating) or [Patreon](https://www.patreon.com/wbotelhos). Thanks! (: diff --git a/lib/rating/models/rating/rate.rb b/lib/rating/models/rating/rate.rb index 1d073fb..d7bbf75 100644 --- a/lib/rating/models/rating/rate.rb +++ b/lib/rating/models/rating/rate.rb @@ -14,6 +14,11 @@ module Rating validates :author, :resource, :value, presence: true validates :value, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 100 } + validates :author_id, uniqueness: { + case_sensitive: false, + scope: %i[author_type resource_id resource_type scopeable_id scopeable_type] + } + def self.create(author:, metadata:, resource:, scopeable: nil, value:) record = find_or_initialize_by(author: author, resource: resource, scopeable: scopeable) diff --git a/spec/models/rate_spec.rb b/spec/models/rate_spec.rb index eb7518b..7553c95 100644 --- a/spec/models/rate_spec.rb +++ b/spec/models/rate_spec.rb @@ -18,4 +18,10 @@ RSpec.describe Rating::Rate do it do is_expected.to validate_numericality_of(:value).is_less_than_or_equal_to(100).is_less_than_or_equal_to 100 end + + it do + expect(object).to validate_uniqueness_of(:author_id) + .scoped_to(%i[author_type resource_id resource_type scopeable_id scopeable_type]) + .case_insensitive + end end