我有一个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 | falseuser1_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模型和独特的组合
发布评论