Search code examples
ruby-on-railsrubyruby-on-rails-4devisesti

Rails STI design - user can be of 2 types


I need some advice on my user model. I came across the STI design and implemented it using devise. This is the basic setup:

class Message < ActiveRecord
    has_one :sender
    has_one :recipient

# Devise user
class User < ActiveRecord

class Sender < User
    belongs_to :message

class Recipient < User
    belongs_to :message

My conundrum is that the same user can be both sender and recipient in different scenarios. I originally set up this domain model such that a message record had a sender_id and recipient_id both of which were simply user_ids without any Railsy relationships defined or devise extras.

My previous solution seemed more flexible but the STI design seems more elegant and if possible I'd like to make it work. As I understand it the convention is that the type field discerns which user is returned. Is there a common solution for this using STI?


Solution

  • Broadly speaking, every time I've ended up implementing multiple types of user model, I've ended up regretting it. As you've already noticed, very quickly you end up with people who want to be both types of user, and suddenly you've got to manage different accounts, repeat logins, duplicate emails, etc.

    I recommend instead setting up a single type of user that has_and_belongs_to_many roles. For simple cases, you can simply create your own role models and logic (which is what I've usually done), but it looks like this gem is pretty well supported as well: https://github.com/RolifyCommunity/rolify