Skip to content

Instantly share code, notes, and snippets.

@Froks15
Created April 26, 2021 17:25
Show Gist options
  • Select an option

  • Save Froks15/6e74ccb8662374e198aeff918bb9a26a to your computer and use it in GitHub Desktop.

Select an option

Save Froks15/6e74ccb8662374e198aeff918bb9a26a to your computer and use it in GitHub Desktop.
How to enforce uniqueness of the HABTM relation between category and thing on the rails side?
class Category < ActiveRecord::Base
has_and_belongs_to_many :things
validates :name, presence: true, uniqueness: true
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.text :description
t.timestamps
end
add_index :categories, :name, unique: true
end
end
class CreateJoinTableCategoryThing < ActiveRecord::Migration
def change
create_join_table :categories, :things, column_options: { null: false } do |t|
t.index [:category_id, :thing_id], unique: true
t.index [:thing_id, :category_id], unique: true
end
end
end
class Thing < ActiveRecord::Base
has_and_belongs_to_many :categories
validates :name, uniqueness: true
validates :name, :lat, :lng, presence: true
end
class CreateThings < ActiveRecord::Migration
def change
create_table :things do |t|
t.string :name
t.text :description
t.timestamps
end
add_index :things, :name, unique: true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment