2017-09-27 3 views
0

私はおもちゃのアプリケーションを構築しようとしていて、解決できないような問題に遭遇しました。テーブルの値のペアが一意であることを強制するにはどうすればよいですか?値ペアに一意性を強制する複合キーを送信する

は、次のスキーマとします

create_table "courses", force: :cascade do |t| 
    t.string "title" 
    t.text "description" 
    t.string "number" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "status", default: 0 
    end 

    create_table "professors", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "status", default: 0 
    end 

    create_table "sections", force: :cascade do |t| 
    t.integer "number" 
    t.integer "max_enrollment" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "professor_id" 
    t.integer "course_id" 
    t.string "room" 
    t.index ["course_id"], name: "index_sections_on_course_id" 
    t.index ["professor_id"], name: "index_sections_on_professor_id" 
    end 

を、私はcourse_idとペアprofessor_idは一意である必要がありますセクションテーブルの一意性制約を作成したかったです。私が掘り下げて見つけた唯一の事は、モデル内でvalidatesキーワードを使用して、単一フィールドの一意性を強制することができるということです... validates_withというキーワードがありますが、バリデーターを書く方法が見つかりません私が探していることをする。どんな助けでも大歓迎です。

答えて

2

データベース(移行中しゃれ)に一意性制約を追加します。

add_index :sections, [:professor_id, :course_id], unique: true 

今もあなたのSectionモデルで検証制約を置く:

validates_uniqueness_of :professor_id, scope: :course_id 

今、あなたのprofessor_idが独自に検証されますcourse_idの範囲内にある。また、データベーステーブルには一意の制約があります。

関連する問題