我如何确保重复的行不通过activerecords添加到我的数据库表? [英] How do I ensure that duplicate rows are not added to my database table via activerecords?

查看:126
本文介绍了我如何确保重复的行不通过activerecords添加到我的数据库表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个表名为票。

So I have a table called votes.

有三列。 VoterID,VoteforID和投票。

There are three columns. VoterID, VoteforID and Vote.

每一列的独特性是不重要然而,同样的行斜面重复两次

The uniqueness of each individual column is not important however, the same row cant repeat twice

有关实例。这是正确的。

For instance. This is correct

Voter_id | Votefor_id |投票

Voter_id | Votefor_id | Vote

1 | 2 | 1

1 | 2 | 1

1 | 3 | 1

1 | 3 | 1

1 | 4 | 1

1 | 4 | 1

2 | 1 | 2

2 | 1 | 2

这是错误的。

Voter_id | Votefor_id |投票

Voter_id | Votefor_id | Vote

1 | 2 | 1

1 | 2 | 1

1 | 2 | 1

1 | 2 | 1

1 | 4 | 1

1 | 4 | 1

2 | 1 | 2

2 | 1 | 2

目前,我做了一个查询语句添加记录只是为了确保相同的行不存在了。当然,有一个更好的解决方案。

Currently, I am doing a select statement before adding records just to make sure that an identical row does not exist. Surely, there is a better solution.

感谢你。

推荐答案

如果数据的完整性是至关重要的,你不应该使用验证,以保证唯一性。它可能会失败。要保证唯一性的唯一方法是使用一个数据库约束。这是因为Rails的 validates_uniqueness 能有比赛的条件。

If data integrity is critical, you should not use a validation to guarantee uniqueness. It can fail. The only way to guarantee uniqueness is to use a database constraint. This is because the Rails validates_uniqueness can have race conditions.

创建迁移添加索引,或更改现有的以反映这一变化:

Create a migration to add the index, or change your existing one to reflect this change:

有关新表:

class CreateVotes < ActiveRecord::Migration
  def change
    create_table :votes do |t|
      t.belongs_to :voter
      t.belongs_to :votefor
      t.string :vote # Choose the correct column type
      t.timestamps
    end
    add_index :votes, [:voter_id, :votefor_id, :vote], unique: true
  end
end

对于现有的表:

For an existing table:

class AddUniqueIndexToVotes < ActiveRecord::Migration
  def change
    add_index :votes,  [voter_id, votefor_id, vote], unique: true
  end
end

现在你可以继续添加验证,所建议的人,如果你想给你的用户的反馈,他们已经投票:

Now you can go ahead and add a validation, as suggested by others, if you want to give your user feedback that they've already voted:

validates :voter_id, uniqueness: { scope: [:votefor_id, :vote] }

这篇关于我如何确保重复的行不通过activerecords添加到我的数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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