devise and multiple “user” models

前端 未结 4 1672
[愿得一人]
[愿得一人] 2020-11-27 09:21

I\'m using rails 3.2 and devise 2.0 and I\'m quite new to Rails.

Requirements

I\'d like to achieve the following:

  • have 2 or more \"user\" mod
4条回答
  •  囚心锁ツ
    2020-11-27 10:00

    I'm in similar shoes as you, after trying all sorts of approaches I went with a single User model, which would belong to polymorphic roles. This seems like the simplest way to achieve single-login.

    The User model would contain the information specific to log-in only.

    The Role model would store fields specific to each role, as well as other associations specific to the role.

    New registrations would be customized for each user type (roles) via individual controllers, and then building nested attributes for the User.

    class User < ActiveRecord::Base
        #... devise code ...
        belongs_to :role, :polymorphic => true
    end
    
    class Member < ActiveRecord::Base
        attr_accessible :name, :tel, :city  #etc etc....
        attr_accessible :user_attributes #this is needed for nested attributes assignment
    
        #model specific associations like  
        has_many :resumes
    
        has_one :user, :as => :role, dependent: :destroy
        accepts_nested_attributes_for :user
    end 
    

    Routes -- just regular stuff for the Member model.

    resources :members
    #maybe make a new path for New signups, but for now its new_member_path
    

    Controller -- you have to build_user for nested attributes

    #controllers/members_controller.rb
    def new
        @member = Member.new
        @member.build_user
    end
    
    def create
        #... standard controller stuff
    end
    

    views/members/new.html.erb

    Sign up for new members!

    <%= simple_form_for @member do |f| %> # user fields <%= f.fields_for :user do |u| %> <%= u.input :email, :required => true, :autofocus => true %> <%= u.input :password, :required => true %> <%= u.input :password_confirmation, :required => true %> <% end %> # member fields <%= f.input :name %> <%= f.input :tel %> <%= f.input :city %> <%= f.button :submit, "Sign up" %> <% end %>

    I would like to point out that there is NO NEED to reach for nested_form gem; since the requirement is that User can only belong_to one type of Role.

提交回复
热议问题