I created to tables:
class CreateWines < ActiveRecord::Migration[6.1]
def change
create_table :wines do |t|
t.string :name
t.string :producer
t.timestamps
end
end
end
class CreateWineItems < ActiveRecord::Migration[6.1]
def change
create_table :wine_items do |t|
t.references :wine, null: false, foreign_key: true
t.string :vintage
t.timestamps
end
add_index :wine_items, [:wine, :vintage], unique: true
end
end
Adding the index for te uniqueness of two columns.
In the WineItem model I added the validation:
validates :wine, uniqueness: {scope: :vintage}
I can insert a WineItem
WineItem.create(wine_id: 1, vintage: "2018")
but if I try another Wine with the same vintage an Unique constraint failed:
WineItem.create(wine_id: 2, vintage: "2018")
ActiveRecord::RecordNotUnique (SQLite3::ConstraintException: UNIQUE constraint failed:
index 'index_wine_items_on_wine_and_vintage')
I only want not to insert same wines with same vintage, and all the references tell me this is the way.
Thanks in advance