Rails联合表自定义验证

时间:2016-07-25 08:51:43

标签: ruby-on-rails validation

我是Rails的新手,这是我目前的情况:我有一个他们所属的用户和团队的联合表,所有团队都有一个名为organization_id的属性,我想确保我可以& #39; t将用户添加到表中,以便表中存在具有相同用户的现有条目,并且它具有与新组织相同的organization_id,即如果我有条目(michael,team_rupert)和team_rupert的organization_id是1,我无法添加一个条目(michael,team_andrew),其中team_andrew的organization_id也是1.这是我的导师和我作为一个习惯拼凑在一起的内容测试,但它似乎没有工作

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :team

  validate :user_can_only_be_in_one_team_per_organization
  validates_uniqueness_of :user_id, scope: :team_id

  def user_can_only_be_in_one_team_per_organization
    organizations = self.user.organizations

    organization_ids = organizations.pluck :id
    unique_organization_ids = organization_ids.uniq

    if organization_ids.count != unique_organization_ids.count
      errors.add :user, 'can\'t be in two teams in the same organization'
    end
  end
end


class User < ApplicationRecord
  has_many :memberships
  has_many :answers, dependent: :destroy
  has_many :teams, through: :memberships
  has_many :organizations, through: :teams

  validates :username, presence: true,
                       uniqueness: true
end

class Organization < ApplicationRecord
  has_many :teams
  has_many :memberships, through: :teams
  has_many :users, through: :memberships

  validates :name, presence: true,
                   uniqueness: true
end

class Team < ApplicationRecord
  has_many :memberships

  has_many :users, through: :memberships
  belongs_to :organization

  validates :name, presence: true,
                   uniqueness: true
end

提前感谢您的帮助。

编辑:我设法解决了这个问题,事实证明新值尚未添加到表中,因此if语句应该检查我们当前的organization_id是否在organization_id数组中。

1 个答案:

答案 0 :(得分:0)

我猜你正在验证用户模型中的内容,我猜你已经设置了适当的用户/团队关系。如果是这样,你可以做以下事情:

def user_can_only_be_in_one_team_per_organization
  teams_in_organization = self.teams.where(organization_id: organization_id) 

  if teams_in_organization.any? 
    errors.add :user, 'can\'t be in two teams in the same organization'
  end
end