问题描述
我有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中执行验证,这意味着您需要使其成为数据库级别
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重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!