从节约的活动记录,并返回被复制的对象prevent重复 [英] Prevent duplicates from saving in active record, and return the object that was duplicated

查看:173
本文介绍了从节约的活动记录,并返回被复制的对象prevent重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个问题,我认为正在引起人们点击提交多次,在我的数据库中的重复记录。我用Rails 3。

I'm having a few issues with duplicate records in my database which I believe are being caused by people clicking submit multiple times. I am using Rails 3.

返回复制的对象,而不是假的

我希望能够prevent重复被添加到我的数据库,但保存副本时,将preFER,如果,被复制的对象返回,而不是假的。原因是,如果有人点击提交几次,我想他们采取向他们展示他们提交了第一次,而不是一个错误页面项目的页面。

I would like to be able to prevent duplicates from being added to my database, but would prefer it if when saving a duplicate, the object that was duplicated was returned, rather than false. The reason being that if someone clicks submit several times, I would like them to be taken to a page showing them the item they submitted first, rather than to an error page.

一式两份的定义

我限定一个重复作为一个条目,其中除了ID的所有字段是相同的,并created_at> Time.now - 1.minute

I'm defining a duplicate as an item in which all the fields except the ID are the same, and created_at > Time.now - 1.minute

否的JavaScript

我会preFER做到这一点的服务器端,而不是仅仅禁用JavaScript中的按钮,因为我不认为数据库的完整性是一个客户端的工作。另外,感觉就像它应在模型中进行的,而不是控制器。我在运行多个乘客,因此任何解决方案,最好应避免并发问题尽可能。一些边缘的情况下重复不会破坏网站虽然。

I would prefer to do this serverside rather than just disabling the button in JavaScript since I don't think database integrity is a client side job. Also, it feels like it should be done in the model, rather than the controller. I'm running multiple passengers, so any solution should ideally avoid concurrency issues as much as possible. A few edge case duplications would not break the site though.

感谢。

推荐答案

ActiveRecord的有动态查找:

ActiveRecord solution

ActiveRecord has a concept of dynamic finders:

User.find_or_create_by_first_name_and_last_name_and_age_and_whatelse(first_name,
    last_name,
    age,
    whatelse)

不知道如何在这里把你的最后一分钟的逻辑。

Not sure how to place your "last minute" logic here.

我会做大致是这样的:

  1. 在用户点击插入新记录。记住它的ID。

  1. On user click insert new record. Memorize its id.

检查是否类似的记录已经张贴在最后一分钟。

Check if similar records were already posted in the last minute.

如果有一个(或多个),删除你的新记录,读取和返回最早的。

If there was one (or several), delete your new record, fetch and return the oldest.

如果没有现有的记录,返回新的。

If there was no existing record, return new one.

这是不是先检查,然后将更好,因为它避免了竞争条件。

It's better than "first check, then insert", because it avoids race conditions.

这将创建一个ID序列一些差距,但。有些人不喜欢这样。 : - )

It will create some gaps in id sequence, though. Some people don't like that. :-)

这篇关于从节约的活动记录,并返回被复制的对象prevent重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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