Override devise registrations controller

前端 未结 5 1786
渐次进展
渐次进展 2020-11-22 00:05

I have added a field to the sign-up form that is based on a different model, see How do I use nested attributes with the devise model for the gory details. This part is work

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 00:51

    I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).

    If you set properly your nested form, at model and view level, everything works like a charm.

    My User model:

    class User < ActiveRecord::Base
      # Include default devise modules. Others available are:
      # :token_authenticatable, :confirmable, :lockable and :timeoutable
      devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
    
      has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id
    
      has_many :organization_memberships
      has_many :organizations, :through => :organization_memberships
    
      # Setup accessible (or protected) attributes for your model
      attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes
    
      accepts_nested_attributes_for :owned_organizations
      ...
    end
    

    My Organization Model:

    class Organization < ActiveRecord::Base
      belongs_to :owner, :class_name => 'User'
      has_many :organization_memberships
      has_many :users, :through => :organization_memberships
      has_many :contracts
    
      attr_accessor :plan_name
    
      after_create :set_owner_membership, :set_contract
      ...
    end
    

    My view : 'devise/registrations/new.html.erb'

    Sign up

    <% resource.owned_organizations.build if resource.owned_organizations.empty? %> <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= devise_error_messages! %>

    <%= f.label :name %>
    <%= f.text_field :name %>

    <%= f.label :email %>
    <%= f.text_field :email %>

    <%= f.label :username %>
    <%= f.text_field :username %>

    <%= f.label :password %>
    <%= f.password_field :password %>

    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation %>

    <%= f.fields_for :owned_organizations do |organization_form| %>

    <%= organization_form.label :name %>
    <%= organization_form.text_field :name %>

    <%= organization_form.label :subdomain %>
    <%= organization_form.text_field :subdomain %>

    <%= organization_form.hidden_field :plan_name, :value => params[:plan] %> <% end %>

    <%= f.submit "Sign up" %>

    <% end %> <%= render :partial => "devise/shared/links" %>

提交回复
热议问题