0

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

1
  • Just out of courisity - why is vintage a string and not an integer? Commented Jul 24, 2021 at 10:02

1 Answer 1

2

the uniqueness is the helper validates that the attribute's value is unique, so your validation should be

validates :wine_id, uniqueness: {scope: :vintage}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes and the index should be add_index :wine_items, [:wine_id, :vintage], unique: true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.