[英]rails uniqueness of on foreign key with scope on date of created_at column
rails uniqueness of on foreign key with scope on date of created_at column Rails在外键上具有唯一性的唯一性,作用域的日期为created_at列的日期
validates :test_id, :uniqueness => { :scope => Date(:created_at)}
The above code wont work. 上面的代码无法正常工作。 But, I need similar thing to validate uniqueness on foreign key with Date(:created_at)
. 但是,我需要类似的东西来通过Date(:created_at)
验证外键的唯一性。
You will need to write a custom validation, there's no way to do this with the built-in uniqueness validator. 您将需要编写一个自定义验证,而内置的唯一性验证器则无法做到这一点。
This one works both with creating new entries, and saving existing ones (by using an existing created_at
if it's there, otherwise we fall back to Date.current
which is the timezone-aware way of getting "today": 这既可以用于创建新条目,也可以用于保存现有条目(如果存在,则使用现有的created_at
,否则我们将退回到Date.current
,这是获取“ today”的时区感知方式:
validate :check_test_id
def check_test_id
date = ( created_at || Date.current ).to_date
if self.class.exists? ["DATE(created_at) = DATE(?) AND test_id = ?", date, test_id]
errors.add :test_id, "is not unique for #{date}"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.