Rails验证多态关联的唯一性

时间:2017-05-17 08:25:02

标签: ruby-on-rails

我有以下内容:

direction:rtl;

正如您所看到的,我的会员模型是双重多态的。我想验证class Membership < ApplicationRecord belongs_to :member, polymorphic: true belongs_to :group, polymorphic: true end 作用范围:member的唯一性。

我希望以下内容能够奏效:

:group

但这会导致错误:

validates :member, uniqueness: { scope: :group }

是否有Rails方法可以执行此操作,还是需要为其编写自定义方法?

4 个答案:

答案 0 :(得分:1)

validates :member_id, :uniqueness => { :scope => [:member_type, :group_id,:group_type] }

有了这个,您可能还希望成员和组的存在都是强制性的,因为nil值将导致重复并且将无法通过唯一性验证

validates :member_type, :member_id, :presence => true
validates :group_type, :group_id, :presence => true

答案 1 :(得分:0)

我使用了罗汉的答案,但为group_id添加了另一个验证

validates :group_id, uniqueness: { :scope => [:group_type, : member_id,: member_type] }
validates :member_id, uniqueness: { :scope => [:member_type, : group_id,: group_type] }

我还添加了一个数据库索引

add_index :memberships, [:group_id, :group_type, :member_id, :member_type], unique: true

答案 2 :(得分:0)

我最终结束了。 (on: :create允许更新)

validate :group_member_uniqueness, on: :create
def group_member_uniqueness
  if Membership.where(group: group, member: member).exists?
    errors[:base] << 'That has already been added'
  end
end

数据库索引

add_index :memberships, [:group_id, :group_type, :member_id, :member_type], unique: true

答案 3 :(得分:-1)

没有内置功能,所以我做了以下内容:

validate :member_is_unique_for_group

def member_is_unique_for_group
  if group.members.include? member
    errors.add(:member, 'already exists for this group')
  end
end