Ruby on rails with different user types

后端 未结 2 1974
失恋的感觉
失恋的感觉 2020-12-20 06:59

I\'m trying to build a application that has different kinds of users, I\'m using authlogic for user authentication.

So I have one user model that has the required f

相关标签:
2条回答
  • 2020-12-20 07:45

    You can create different profile tables and just tie the profile to the user. So for each user type you can create a table and store the specific info there and have a user_id column to point back to users.

    class User < ActiveRecord::Base
      has_one :type_1
      has_one :type_2
    end
    
    class Type1 < ActiveRecord::Base
      belongs_to :user
    end
    
    class Type2 < ActiveRecord::Base
      belongs_to :user
    end
    

    Now this isn't very DRY and could lead to problems if you are constantly adding user types. So you could look into polymorphism.

    For polymorphism, the users table would define what type the user is (profileable_id and profileable_type). So something like this:

    class User < ActiveRecord::Base
      belongs_to :profileable, :polymorphic => true
    end
    
    class Type1 < ActiveRecord::Base
      has_one :user, :as => :profileable
    end
    
    class Type2 < ActiveRecord::Base
      has_one :user, :as => :profileable
    end
    

    Then there is a third option of STI (single table inheritance) for the user types. But that doesn't scale well if the user type fields differ dramatically.

    0 讨论(0)
  • 2020-12-20 07:57

    The best approach I saw it here http://astockwell.com/blog/2014/03/polymorphic-associations-in-rails-4-devise/

    0 讨论(0)
提交回复
热议问题