2016-07-25 84 views
0

我是Rails的新手,这里是我目前的情况:我有一个他们所属的用户和团队的联合表,所有团队都有一个名为organization_id的属性,我想确保我可以' •将一个用户添加到表中,以便表中存在具有相同用户的现有条目,并且它具有与新条目相同的organization_id,即如果我有条目(michael,team_rupert)和team_rupert的organization_id是1,我可以再增加一个条目(迈克尔,team_andrew),其中team_andrew的的organization_ID也为1。这里是我的导师,我张罗为自定义的测试,但它似乎没有工作Rails联合表自定义验证

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数组中。

+0

我很困惑。如果rupert团队的organization_id为1,team andrew的组织ID将不会为1.您的意思是您想避免连接表中的重复项? –

+0

请将您的模型及其关联添加到问题中,以便更容易理解您的问题。 – aBadAssCowboy

+0

组织可以有许多团队,团队可以有很多用户,对不起,忘了提到这一点。 – Robert

回答

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