HABTM duplicate records

后端 未结 4 680
醉梦人生
醉梦人生 2020-12-30 13:18

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

4条回答
  •  梦毁少年i
    2020-12-30 14:16

    Creating new Model GameTheme for validation purpose is not a good idea. We can validate itself in migration.

    Theme Model:

    class Theme < ActiveRecord::Base
      has_and_belongs_to_many :games,
        :association_foreign_key => 'theme_id',
        :class_name => 'Theme',
        :join_table => 'games_themes'
    end
    

    Game Model:

    class Theme < ActiveRecord::Base
      has_and_belongs_to_many :games,
        :association_foreign_key => 'game_id',
        :class_name => 'Game',
        :join_table => 'games_themes'
    end
    

    games_themes migration: You can add uniqueness to join table, Have a look here for more detail.

    class GamesThemesTable < ActiveRecord::Migration
      def self.up
        create_table :games_themes, :id => false do |t|
          t.references :game
          t.references :theme
        end
    
        add_index :games_themes, [:theme_id, :game_id], :unique => true
    
      end
    
      def self.down
        drop_table :games_themes
      end
    end
    

提交回复
热议问题