[英]Rails uniqueness validation based on relation
我有兩個模特
create_table "registrations", :force => true do |t|
t.integer "orientation_id"
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "student_id"
...
end
create_table "orientations", :force => true do |t|
t.date "class_date"
t.text "class_time"
t.integer "seats"
t.boolean "active", :default => true
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
我想在我的注冊模型中創建一個驗證,該驗證說student_id在每個方向上必須唯一。
如果我正確理解了您的問題,則需要validates_uniqueness_of
的scope
選項。
在您的Registration
模型中,
Class Registration < ActiveRecord::Base
......
validates_uniqueness_of :student_id, scope: :orientation_id
end
而且,您應該生成一個遷移以添加此內容
add_index :registration, [ :student_id, :orientation_id ], :unique => true
更多信息在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.