Rails - 2 种用户类型的应用程序设计 [英] Rails - application design for 2 user types

查看:38
本文介绍了Rails - 2 种用户类型的应用程序设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 ruby​​ on rails 应用程序,它将有两种不同类型的用户(假设卖家和买家).我正在考虑使用单表继承,但最终我决定创建 2 个单独的模型(我相信在我的情况下这是更好的解决方案).

I am writing ruby on rails app, that will have 2 different types of users (let's say sellers and buyers). I was thinking about using single table inheritance, but ultimately I decided to crate 2 separate models (I believe it's better solution in my case).

问题是当我尝试创建私人消息模型时(卖家和买家都可以相互联系).通常,我只会生成具有 3 个字段(from_user_id to_user_id 和 content)的名为 message 的模型.这在我的情况下不起作用,因为可能有 2 个用户具有相同的 ID(1 个卖家和 1 个买家).

The problem is when I try to create private message model (both sellers and buyers can contact each other). Typically I would just generate model called message with 3 fields (from_user_id to_user_id and content). This will not work in my case, because there might be 2 users with the same id (1 seller and 1 buyer).

我正在考虑使用电子邮件来识别发送者和接收者,但电子邮件不是我的主键,所以我想我将无法在消息模型中使用它作为外键.哦 - 顺便说一句,确保电子邮件在卖家和买家表中都是唯一的最佳方法是什么(换句话说,用户不能通过一封电子邮件作为卖家和买家加入)

I was thinking about using e-mail to identify sender and receiver, but e-mail is not my primary key, so I guess I won't be able to use it a foreign key in message model. Oh - btw, what is the best way to make sure that e-mails are unique in both sellers and buyers tables (in other words user can't join as a seller and buyer from one email)

有什么想法可以优雅地解决我的问题吗?

Any ideas how I can elegantly solve my problem?

推荐答案

您正在寻找的是多态关联.这允许您通过指定 ID 以及其他对象的类来拥有一个可以通过相同关系属于多个其他模型的模型.例如,如果买家 ID 3 向卖家 ID 5 发送消息,您的消息表将以如下行结束:

What you are looking for is a polymorphic association. What this allows you to do is have a model that can belong to multiple other models through the same relationship by specifying the ID as well as the Class of the other object. For example, if buyer ID 3 sends a message to seller ID 5, your message table will end up with a row like:

sender_id = 3
sender_type = Buyer
receiver_id = 5
receiver_type = Seller

要在活动记录中完成此操作,您的模型将如下所示:

To accomplish this in active record, your models will look like the following:

class Message < ActiveRecord::Base
  belongs_to :sender, :polymorphic => true
  belongs_to :receiver, :polymorphic => true
end

class Buyer < ActiveRecord::Base
  has_many :sent_messages, :class_name => "Message", :as => :sender
  has_many :received_messages, :class_name => "Message", :as => :receiver
end

class Seller < ActiveRecord::Base
  has_many :sent_messages, :class_name => "Message", :as => :sender
  has_many :received_messages, :class_name => "Message", :as => :receiver
end

这篇关于Rails - 2 种用户类型的应用程序设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆