HABTM重复记录

use*_*382 7 ruby ruby-on-rails associations ruby-on-rails-3

我有2个模型Game&Theme他们有一个has_and_belongs_to_many关联.我已经尝试了许多解决方案来防止games_themes表中的重复记录,但没有解决方案可行.问题是,games_themes是一个表,但它不是一个模型,所以我无法找到一种方法来有效地运行验证.

这是我试过的解决方案

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
Run Code Online (Sandbox Code Playgroud)

Ric*_*eck 14

您应该使用数据库级验证:

#new_migration
add_index :games_themes, [:game_id, :theme_id], :unique => true
Run Code Online (Sandbox Code Playgroud)

HABTM

这将阻止您在数据库中保存任何重复数据.减轻Rails的负担并确保您只拥有游戏或主题.问题是因为HABTM没有模型,没有可以在Rails中执行的验证,这意味着你需要使它成为db级别

正如评论中所提到的,这意味着你必须像这样处理从db引发的异常:

#app/controllers/games_controller.rb
def create
    #creation stuff here
    if @game.save
        #successful save
    else
        #capture errors
    end
end
Run Code Online (Sandbox Code Playgroud)