Rails - application design for 2 user types

风格不统一 提交于 2019-12-04 19:17:12

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

Why do you decided to not have a single User model? Considered all the issues caused by having these users in two separated tables I would have a User model and extend this model to have a Buyer model and a Seller model.

I think a buyer or a seller is still a user of your application, this resolves the problem of the message from a user to another too.

class User < ActiveRecord::Base
  # Remember to add a "type" column in the users table
end

class Seller < User
end

class Buyer < User
end

The messages are now between users, no matter which kind of user.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!