[英]Uniqueness validation not working on has_many :though association on rails 5
楷模
class User < ApplicationRecord
has_many :memberships
has_many :pages, through: :memberships
end
class Page < ApplicationRecord
has_many :memberships
has_many :users, through: :memberships
end
class Membership < ApplicationRecord
belongs_to :user
belongs_to :page
validates :page_id, uniqueness: { scope: :user_id}
end
能夠在頁面和用戶頁面上創建多個用戶,就像沒有調用驗證一樣。
要在關聯模型中觸發驗證,您需要使用validates_associated
:
class User < ApplicationRecord
has_many :memberships
has_many :pages, through: :memberships
validates_associated :memberships
end
class Page < ApplicationRecord
has_many :memberships
has_many :users, through: :memberships
validates_associated :memberships
end
class Membership < ApplicationRecord
belongs_to :user
belongs_to :page
validates :page_id, uniqueness: { scope: :user_id}
end
這可能是一個真正的陷阱,因為隱式創建關聯時不會調用它們的驗證。
另外,創建一個復合數據庫索引以防止可能出現的競爭狀況是一個好主意:
class AddCompoundIndexToMemberships < ActiveRecord::Migration[5.0]
def change
add_index :memberships, [:page_id, :user_id], unique: true
end
end
這樣可以確保在數據庫級別上無法創建兩個相同的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.