简体   繁体   English

唯一性验证导轨 4

[英]Uniqueness validation rails 4

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.我有两种类型的评论,“CommentType.internal”可以多次添加到评论表中,“CommentType.final”可以保存一次,但可以通过更新操作进行修改。

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.我可以使用最终的 comment_type_id 保存一条记录,但是当我想创建另一个记录时,无论我拥有哪个 commentary_type_id,它仍然无法通过此唯一性验证。

What am I doing wrong?我究竟做错了什么?

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
                          )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM