HABTM重复记录

用户名

我有2个模型GameTheme并且它们具有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
理查德·派克

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

#new_migration
add_index :games_themes, [:game_id, :theme_id], :unique => true

HABTM

这将防止您将任何重复的数据保存在数据库中。减轻Rails的负担,确保您只有游戏或主题。问题是因为HABTM没有模型,因此无法在Rails中执行验证,这意味着您需要使其成为数据库级

如注释中所述,这意味着您必须像这样处理从数据库引发的异常:

#app/controllers/games_controller.rb
def create
    #creation stuff here
    if @game.save
        #successful save
    else
        #capture errors
    end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章