Rails模型和独特的组合 [英] Rails Models and unique combinations
问题描述
我有一个Rails应用程序,其中有一个名为friendrequests
的表.看起来像这样:
I have a Rails app which has a table called friendrequests
. It looks like this:
user1_id:integer user2_id:integer hasaccepted:boolean
我正在创建一个添加朋友的选项,但是一个Friendrequest只能发送一次.因此,数据库的数据中不能包含这样的内容:
I'm creating an option to add friends, but a friendrequest can only be send once. So you cannot have something like this in the database's data:
user1_id | user2_id | hasaccepted
1 | 2 | false
1 | 2 | false
或
user1_id | user2_id | hasaccepted
1 | 2 | false
2 | 1 | false
user1_id/user2_id组合必须是唯一的,而不是列本身,因此这是可能的:
The user1_id/user2_id combination must be unique, not the columns themselves, so this would be possible:
user1_id | user2_id | hasaccepted
1 | 2 | false
1 | 3 | false
是否可以在模型中定义它?我该怎么办?
Is it possible to define this in a model? How can I do this?
推荐答案
对于第一种情况,在您的FriendRequest
模型中,使用validates_uniqueness_of(:user1_id, :scope => :user2_id)
.您可能还需要相反的操作.对于第二种情况,我将覆盖FriendRequest
中的#validate
并在那里进行检查(请参见 API文档,详细了解该方法的执行方式.
For the first case, in your FriendRequest
model, use validates_uniqueness_of(:user1_id, :scope => :user2_id)
. You might also need the reverse. For the second case I'd override #validate
in FriendRequest
and do a check in there (see the API docs for details on how the method should perform).
这篇关于Rails模型和独特的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!