2016-07-25 12 views
0

私はRailsを使い始めましたが、私の現在の状況です:ユーザーとチームのジョイントテーブルがあり、すべてのチームにorganization_idという属性があります。同じユーザーを持つテーブルに既存のエントリがあり、新しいものと同じorganization_idを持つようにユーザーをテーブルに追加します。つまり、エントリ(michael、team_rupert)があり、team_rupertのorganization_idが1の場合、 「Tはteam_andrewのORGANIZATION_IDも1であるエントリ(マイケル、team_andrew)、ここでは私の師匠と私はカスタムテストとしてかき集め何だが、事前に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 

おかげで動作していないようを追加しますあなたの助け。

EDIT:私はそれを修正することができました。新しい値がまだテーブルに追加されていないことが判明しました。したがって、if文は現在のorganization_idがorganization_id配列にあるかどうかを確認する必要があります。

+0

私は混乱しています。 team 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