2011-07-26 34 views
1
def User 
    has_many :conversation_participants 
end 

def Conversation 
    has_many :conversation_participants 
end 

def ConversationParticipant 
    belongs_to :conversation 
    belongs_to :user 
end 

我想將驗證添加到ConversationParticipant,以便一個對話(conversation_id)只能存在一個相同用戶(user_id)的記錄。所以這將是無效的:2xbelongs_to,B唯一

id user_id conversation_id 
1 1  1 
2 2  1 
3 1  1 # <-- invalid 
4 3  1 

任何關鍵字,描述這個問題(未來Googlin')讚賞。

編輯:一些代碼

c = Conversation.first 
c.conversation_participants.build(:user => User.first) 
c.save # => true 

c.conversation_participants.build(:user => User.first) 
c.save # => false 

回答

1

可以傳遞一個:uniq的進入的has_many:

def User 
    has_many :conversation_participants, :uniq => true 
end 

def Conversation 
    has_many :conversation_participants, :uniq => true 
end 

def ConversationParticipant 
    belongs_to :conversation 
    belongs_to :user 
end 

RoR Associations (uniqueness constraint is about 3/4 of the way down).

+0

「在上述情況下還存在兩個讀數。然而,person.posts只顯示一個帖子,因爲集合只加載唯一的記錄。「我不知道它是否確實阻止了我沒有嘗試的唯一性要求的記錄(因爲Andy's是完美的我)。 –

+0

此外,我相信這個驗證屬於ConversationParticipant模型,但我想這只是個人偏好。 –

相關問題