所以我有一个名为 votes 的表。
共有三列。 VoterID、VoteforID 和投票。
每一列的唯一性并不重要,但是同一行不能重复两次
例如。这是正确的
选民编号 |投票编号 |投票
1 | 2 | 1
1 | 3 | 1
1 | 4 | 1
2 | 1 | 2
这是错误的。
选民编号 |投票编号 |投票
1 | 2 | 1
1 | 2 | 1
1 | 4 | 1
2 | 1 | 2
目前,我在添加记录之前执行 select 语句只是为了确保不存在相同的行。当然,还有更好的解决方案。
谢谢。
最佳答案
如果数据完整性至关重要,则不应使用验证来保证唯一性。它可能会失败。保证唯一性的唯一方法是使用数据库约束。这是因为 Rails validates_uniqueness
可以有竞争条件。
创建迁移以添加索引,或更改现有的迁移以反射(reflect)此更改:
对于新表:
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
对于现有表:
class AddUniqueIndexToVotes < ActiveRecord::Migration
def change
add_index :votes, [voter_id, votefor_id, vote], unique: true
end
end
现在,如果您想向用户反馈他们已经投票,您可以按照其他人的建议继续添加验证:
validates :voter_id, uniqueness: { scope: [:votefor_id, :vote] }
关于ruby-on-rails - 如何确保不会通过 activerecords 将重复行添加到我的数据库表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722205/