2016-07-25 79 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