1

楷模

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

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

4

1 回答 1

3

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

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

于 2017-09-27T13:09:37.627 回答