防止Rails中重复记录的正确方法 [英] Correct way of prevent duplicate records in Rails

查看:41
本文介绍了防止Rails中重复记录的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,我有这个:

In my model I have this:

validates :name, :presence => true, :uniqueness => true

在我的控制器中,我有:

In my controller I have:

...
if @location.save
    format.html { redirect_to @location, :notice => 'Location was successfully created.' }
    format.json { render :json => @location, :status => :created }
...

如果表中还没有具有此名称的记录,则成功创建记录.我认为在插入可能重复的记录之前进行检查而不是依赖数据库约束是一种很好的做法?

which successfully creates a record if there isn't already a record with this name in the table. I think it's good practice to check before inserting a possibly duplicate record instead of relying on the DB constraints?

我想我应该向控制器添加一些东西来检查?这样做的正确方法是什么?

I guess I should add something to the controller to check? What's the correct way to do this?

非常感谢.

推荐答案

验证在记录到达数据库之前由 Rails 完成.如果记录未通过验证,则不会保存,并且 .save 将返回 false,这将导致控制器的 else 子句执行.该子句通常会重新呈现提交的页面,并显示错误以便更正.

Validations are done by Rails before the record would hit the database. If the record fails a validation, it won't save, and .save will return false, which will cause the else clause of your controller to execute. That clause usually rerenders the page that was submitted, with the errors displayed so they can be corrected.

假设你的控制器是这样构建的,你不需要做任何其他事情.当然,您应该确保所有数据库约束都反映在您的验证中,否则记录可能会通过验证,但在保存时违反约束会产生错误.

Assuming that your controller is built like that, you don't need to do anything else. You should, naturally, make sure that any database constraints are mirrored in your validations, otherwise a record might pass validations but produce an error from violating a constraint when it was saved.

这篇关于防止Rails中重复记录的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆