Sunday, 15 February 2015

How would I implement a multi-type user system for Rails? -



How would I implement a multi-type user system for Rails? -

i'm creating rails application users can sign checking box in form either "person" or "organization". i'm struggling find way implement rails. both of these user types have same authorization. have no thought if want utilize string or boolean info type in activerecord database. also, need set in model (user.rb) , controller in order validate , implement respectively?

there many ways implement this; depends on needs are. inquire yourself: "do people , organizations share same attributes?"

ar enum

if do, thing differentiates 2 role (or whatever want phone call it), i.e., person or organization. scenario, rails 4.1 provides ar enums. simplest solution, go this:

class user < activerecord::base enum role: [ :person, :organization ] # @user.role => 'person', @user.person? => true end polymorphic association

on other hand, if people , organizations share attributes, might consider using polymorphic association (if people , organizations share no attributes—not role—they should 2 different models). base of operations model should contain attributes both people , organizations share. person/organization models should contain attributes specific model.

# mutual attributes class user < activerecord::base belongs_to :profile, polymorphic: true def self.roles %w(person organization) end end # person-specific attributes class personprofile < activerecord::base has_one :user, as: :profile, dependent: :destroy end # organization-specific attributes class organizationprofile < activerecord::base has_one :user, as: :profile, dependent: :destroy end

for user signup, can create users#new , users#create actions. in user signup form (perhaps app/views/users/new.html.erb), utilize select_tag allow user specify role. then, utilize determine kind of profile attach user model. illustration (users#create):

def create @user = user.new(user_params) if role = params[:role] # homecoming http 400 head :bad_request , homecoming unless user.roles.include?(role) # assign user's profile @user.profile = "#{role.capitalize}profile".constantize.new else # come in own logic here end @user.save ? redirect_to(@user) : render(:new) end

the handling of sessions (user signin/signout), in opinion, should handled in separate sessionscontroller.

ruby-on-rails types rails-activerecord

No comments:

Post a Comment