How to add custom fields to devise_invitable invite form

231 Views Asked by At

I need to set the User's role upon inviting a User using devise_invitable. I've read through the answers on SO on how to accomplish this as well as the docs and I've had no luck. Every post but one is pretty dated.

Why isn't the role field populating in the view? Only the email field is showing. Do I need to add something to my application_controller?

routes.rb

Rails.application.routes.draw do
  resources :assignments
  resources :games

  devise_for :users, :controllers => {registrations: 'registrations', invitations: 'users/invitations' }

  root 'main#index'
end

invitations_controller.rb

class Users::InvitationsController < Devise::InvitationsController
    before_action :configure_permitted_parameters

    protected
  
    # Permit the new params here.
    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:invite, keys: [:email, :role])
    end
end

app/views/devise/invitations/new.html.erb

<h2><%= t "devise.invitations.new.header" %></h2>

<%= simple_form_for(resource, as: resource_name, url: invitation_path(resource_name), html: { method: :post }) do |f| %>
  <%= f.error_notification %>

  <% resource.class.invite_key_fields.each do |field| -%>
    <div class="form-inputs">
      <%= f.input field %>
    </div>
  <% end -%>

  <div class="form-actions">
    <%= f.button :submit, t("devise.invitations.new.submit_button") %>
  </div>
<% end %>
1

There are 1 best solutions below

2
Abdur Rehman Sajid On

Add virtual attribute(attr_accessor: role ) in user.rb then you will be able to use it in

class User < ApplicationRecord
    attr_accessor :role   
end