Reputation: 26192
I have this uniqueness validation in my model:
validates_uniqueness_of :source_id,
scope: [:year_id],
conditions: -> { where(comment_type_id: CommentType.final.id) },
message: %(
There can be only one final comment per year
)
I have 2 types of comment, the 'CommentType.internal' which can be added to the commentary table many times, and 'CommentType.final' which can be saved once, but via update action it can be modified.
I'm able to save the one record with the final comment_type_id, but when I want to create another regardless of which commentary_type_id I have it still fails on this uniqueness validation.
What am I doing wrong?
Upvotes: 2
Views: 54
Reputation: 26192
This worked for me, I ll answer for anyone else facing the same issue :
validates_uniqueness_of :comment_type_id,
scope: [:year_id, :source_id],
if: ->(cmt) { cmt.comment_type_id == CommentType.final.id) },
message: %(
There can be only one final comment per year
)
Upvotes: 2