在唯一性验证条件中使用记录属性值

时间:2017-06-29 14:18:07

标签: ruby-on-rails

我想在此记录created_at之前的3个月内检查记录属性的唯一性,如:

validates :number, uniqueness: { conditions: -> { where('created_at > ?', Time.now - 3.months)}}

但我不是Time.now而是使用经过验证的记录created_at值。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

你所写的内容应该已经有效,如果你需要相反的话,那就预期了。

你可以稍微重构一下,创建一个scope来定义3个月内创建的所有项目。

scope :created_within_three_month, -> { where('created_at <= ?', 3.months.ago) }

然后你的validates写得很好。

validates :number, uniqueness: true, conditions: :created_within_three_month

注意:但如果我是你,我会在你的模型上创建state,然后编写一个rake任务,将archived所有3岁以上的记录放在上面个月。

然后我将验证:

validates :number, uniqueness: true, conditions: -> { where.not(state: 'archived') }
相关问题