在创建记录之前,我希望验证是否不存在类似的记录。
当我说“相似”时,我想比较3-4列,看看它们是否具有相同的值,如果它们具有相同的值,则不保存和报告验证消息。
这只发生在创建过程中,在更新过程中可能会出现重复,但是在创建过程中,我不想允许重复。
,我该怎么做?也就是说,哪个回调对此最好,以及如何向验证错误集合添加?
发布于 2013-11-17 20:24:08
我会这样做:
validate :has_similar_record, :on => :create
...
private
def has_similar_record
if <Class>.find_by_column1_and_column2_and_column3(column1, column2, column3).present?
self.errors.add(:base, "record already exists with similar values")
end
end发布于 2013-11-18 12:33:47
您可以使用first_or_create链接多个where子句,如果不存在,则创建它。
就像。
Post.where(author: 'tom').where(subject: 'Rails is awesome').first_or_create!这将引发异常。
这里有更多信息,(假设您使用的是Rails 3.2+)
create
更新
对不起,我误解了你的问题。如果对象已经存在,则不希望创建它。因此,您可以使用exists?方法,该方法可以在模型或关系上调用。
就像。
post_exists = Post.where(author: 'tom').where(subject: 'Rails is awesome').exists?如果它返回true,我们可以向self添加错误
self.errors.add(:post, "already exists") if post_exists == true这可以包装在自定义验证器方法中,如果post_exists为真,该方法将返回false。
def validate_existence_of_post
post_exists = Post.where(author: 'tom').where(subject: 'Rails is awesome').exists?
if post_exists == true
self.errors.add(:post, "already exists")
return false
end
true
end关于querying.html#existence-of-objects存在的更多信息
https://stackoverflow.com/questions/20035574
复制相似问题