Created
April 26, 2021 17:25
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Category < ActiveRecord::Base | |
| has_and_belongs_to_many :things | |
| validates :name, presence: true, uniqueness: true | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Thing < ActiveRecord::Base | |
| has_and_belongs_to_many :categories | |
| validates :name, uniqueness: true | |
| validates :name, :lat, :lng, presence: true | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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