def User
has_many :conversation_participants
end
def Conversation
has_many :conversation_participants
end
def ConversationParticipant
belongs_to :conversation
belongs_to :user
end
1つの会話(conversation_id)の同じユーザー(user_id)のレコードが1つしか存在しないようにConversationParticipantに検証を追加したいと思います。だから、これは無効になります:2xbelongs_to、AユニークB
id user_id conversation_id
1 1 1
2 2 1
3 1 1 # <-- invalid
4 3 1
(将来Googlinのために)この問題を説明する任意のキーワードが高く評価されています。
EDIT:has_manyのにUNIQ:いくつかのコード
c = Conversation.first
c.conversation_participants.build(:user => User.first)
c.save # => true
c.conversation_participants.build(:user => User.first)
c.save # => false
「は、上記の場合において、2個の読み取り値が残ってい。しかし、person.postsは、コレクションにユニークなレコードのみがロードされるため、1つのポストしか表示しません。「アンディーが完璧だったので、私が試したことのない独自の要件を満たしていないレコードを防ぐことはできません。私) –
さらに、私はこの検証がConversationParticipantモデルに属すると信じていますが、それは個人的な好みだと思います:) –