简体   繁体   English

Rails验证多态关联的唯一性

[英]Rails validating uniqueness of polymorphic association

I have the following: 我有以下几点:

class Membership < ApplicationRecord
  belongs_to :member, polymorphic: true
  belongs_to :group, polymorphic: true
end

As you can see my Membership model is doubly polymorphic. 如您所见,我的Membership模型是双重多态的。 I want to validate the uniqueness of :member scoped by :group . 我想验证:group的唯一性:member

I was hoping the following would work: 我希望以下方法能起作用:

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

But this causes an error: 但这会导致错误:

NameError: uninitialized constant Membership::Member

Is there a Rails way of doing this, or do I need to write a custom method for it? 有Rails的方式可以做到这一点,还是我需要为此编写一个自定义方法?

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

With this, you might also want to make presence of member and group both mandatory, as nil values will lead to duplicates and will fail the uniqueness validation 这样,您可能还希望使成员和组都必须存在,因为nil值将导致重复并且将使唯一性验证失败

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

I used rohan's answer but added another validation for group_id 我使用了罗汉的答案,但为group_id添加了另一个验证

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

I also added a DB index 我还添加了一个数据库索引

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

I ended up with this. 我结束了这个。 ( on: :create allows updating) 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

DB index 数据库索引

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

There is no built-in for this, so I did the following: 没有内置的功能,所以我做了以下工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM