Rails模型和独特的组合

编程入门 行业动态 更新时间:2024-10-24 06:31:58
本文介绍了Rails模型和独特的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-29 22:57:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647877.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   模型   独特   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!