HABTM 重复记录 [英] HABTM duplicate records
问题描述
我有 2 个模型 Game
&Theme
并且它们有一个 has_and_belongs_to_many 关联.我尝试了许多解决方案来防止 games_themes
表中的重复记录,但没有任何解决方案有效.问题是,games_themes
是一个表格,但它不是一个模型,所以我无法找到一种有效地对其进行验证的方法.
I have a 2 models Game
& Theme
and they have a has_and_belongs_to_many association. I have tried many solutions to prevent duplicate records in the games_themes
table, but no solutions work. The problem is, games_themes
is a table, but it is not a model, so I can't figure out a way to run validations on it effectively.
这是我尝试过的解决方案
Heres a solution I tried
class Theme < ActiveRecord::Base
has_and_belongs_to_many :games, :uniq => true
end
class Game < ActiveRecord::Base
has_and_belongs_to_many :themes, :uniq => true
end
推荐答案
您应该使用数据库级验证:
You should use database-level validation:
#new_migration
add_index :games_themes, [:game_id, :theme_id], :unique => true
<小时>
HABTM
这将防止您在数据库中保存任何重复数据.减轻 Rails & 的负担确保您只有游戏或主题.问题是因为 HABTM 没有模型,所以您无法在 Rails 中执行验证,这意味着您需要将其设为 db 级别
This will prevent you saving any duplicate data in the database. Takes the burden off Rails & ensures you only have game or theme. The problem is because HABTM doesn't have a model, there's no validation you can perform in Rails, meaning you need to make it db-level
正如评论中提到的,这意味着您必须像这样处理从数据库引发的异常:
As mentioned in the comments, this means you'll have to handle the exceptions raised from the db like this:
#app/controllers/games_controller.rb
def create
#creation stuff here
if @game.save
#successful save
else
#capture errors
end
end
这篇关于HABTM 重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!