唯一性验证不适用于has_many:尽管在rails 5上有关联

时间:2017-09-27 11:39:57

标签: ruby-on-rails ruby validation has-many-through validates-uniqueness-of

模型

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

能够在用户的页面和页面上创建多个用户,就像验证没有被调用一样。

1 个答案:

答案 0 :(得分:1)

要在关联模型中触发验证,您需要使用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

这可能是一个真正的问题,因为关联时的验证在隐式创建时不会被调用。

此外,最好创建一个阻止possible race conditions的复合数据库索引:

class AddCompoundIndexToMemberships < ActiveRecord::Migration[5.0]
  def change
    add_index :memberships, [:page_id, :user_id], unique: true
  end
end

这确保在数据库级别上不能创建两个相同的行。