Search code examples
ruby-on-railsdatabasedeviseuser-registration

Rails & Devise: modifying a field before saving form to DB


My configuration:

Devise

Devise Views expanded out

Using a separate Registrations controller (moved the files from views/devise/registrations to views/registrations)

I have a hidden field in the new registration form that is supposed to be filled after the form is submitted, but the value is not being saved to the database.

Here's what I have:

In routes.rb:

devise_for :users, :controllers => { :registrations => 'registrations' }, :path => '', :path_names => { :sign_in => "login", :sign_up => "request_invite" }

In views/regiistrations/new, I have company_id defined as a hidden field

In models/user.rb, I have:

attr_accessible: company_id

In registrations_controller.rb, I have:

class RegistrationsController < Devise::RegistrationsController
  ........
def create
  @user = User.new(params[:user])
  company_id = params[:user][:company] + "_" + params[:user][:ssid]
  params[:user][:company_id] = company_id.downcase

  respond_to do |format|
    if @user.save
      flash[:notice] = "New user added"
      format.html { redirect_to root_url }
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end 
.....

The contents of the form are saved to the DB, but not company_id. I verified that company_id is actually being created, and is actually passed on as part of user params. Did the save to DB occur somewhere before I computed company_id? I saw a bunch of StackOverflow Q/A on similar topics, but nothing worked or fit what I am trying to do. Newbie here, so perhaps I am not familiar with all the things to look for, as I imagine that this something people do on regular basis.

UPDATE:

To make sure the Q/A is complete, following is the correct code:

class RegistrationsController < Devise::RegistrationsController
........
  def create
    @user = User.new(params[:user])
    company_id = params[:user][:company] + "_" + params[:user][:ssid]
    @user.company_id = company_id.downcase

    respond_to do |format|
      if @user.save
        flash[:notice] = "New user added"
        format.html { redirect_to root_url }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end 
  .....

Solution

  • Change this line: params[:user][:company_id] = company_id.downcase

    To this: @user.company_id = company_id.downcase

    Changing the params does nothing, as you have already created the object using the previous hash values.