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)的一条记录。所以这将是无效的:
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
答案 0 :(得分:4)
validates_uniqueness_of:user_id,:scope =&gt; [:conversation_id]
或性感验证:
验证:user_id,:uniqueness =&gt; {:scope =&gt; [:conversation_id]}
http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000086
答案 1 :(得分: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).