mardi 11 avril 2017

Rails Devise - Update User with Associated Model

Good day,

I have a devise users model and in edit profile page I want to add a custom field called "add verification documents" which takes in multiple documents(pdf's) that are uploaded in edit profile page .A User can upload multiple documents.

user.rb

 class User < ActiveRecord::Base
 has_many :verification_documents
 end

routes.rb

      devise_for :users,
         path: '',
         path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'sign-up', edit: 'profile'},
         controllers: {
             omniauth_callbacks: 'omniauth_callbacks',
             registrations: 'registrations'
         }

My Requirement is similar to Rails Devise - Register User with Associated Model , But Instead of address attributes, here I want to upload multiple verification verification documents to the verification_documents model during update action of the devise user model.

views/devise/registrations/edit.html.erb

    <div class="row">
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {method: :put}, multipart: true) do |f| %>
   <div class="form-group">
            <%= f.text_field :fullname, autofocus: true, placeholder: "Full Name *", class: "form-control" %>
          </div>

          <div class="form-group">
            <%= f.email_field :email, placeholder: "Email *", class: "form-control" %>
          </div>
           <span class="btn btn-default  btn-file btn-green pad_small">Upload Verification Documents
                <input type="file" accept="application/pdf" name="input-file-preview"/>  
                  <%= file_field_tag "verification_documents[]", type: :file, multiple: true %>
                </span> 
     <div class="actions">
            <%= f.button "Save", class: "btn btn-green pad_small" %>
          </div>

verification_document.rb

  class VerificationDocument < ActiveRecord::Base
     belongs_to :user
     has_attached_file :verification_documents                
     validates_attachment_content_type :verification_documents, {:content_type => %w( application/pdf )} 
 end

Is it possible to update something like below in RegistrationsController as ?

RegistrationsController < Devise::RegistrationsController

      def update
      if @user.update(user_params)
    if params[:verification_documents]
    params[:verification_documents].each do |doc|
      @user.verification_documents.create(verification_documents: doc)
    end
   end
   redirect_to root_path, notice: "Updated..."
   else
   render :edit
   end

In application_controller.rb I have ,

 def configure_permitted_parameters
   devise_parameter_sanitizer.permit(:sign_up, keys: [:fullname, :subscribe])
   devise_parameter_sanitizer.permit(:account_update, keys: [:fullname, :reset_password_token, :verification_documents])

 end

Any Help is Highly Appreciated.Thanks in Advance!

Aucun commentaire:

Enregistrer un commentaire