且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HABTM重复记录

更新时间:1970-01-01 07:56:42

您应使用数据库级验证:

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