问题
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).
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?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/9517406/rails-application-design-for-2-user-types