Arslan Ali
Arslan Ali

Reputation: 17812

How to send a variable from an action without using the URL in Rails?

How to send a variable/parameter from an action without using the URL?

I need to create a user in multiple steps, and the user is created on the 2nd step. I need to receive the email of the user from the first step.

One first step, I receive the email in params, and use this line of code: redirect_to new_user_registration_path(email: params[:email]) to send it out to the next page/action.

For some reasons, I have been told that I can't use emails in URLs, so now I need to send the email under the hood which surely is possible through the POST method, but redirect_to doesn't support POSTs requests.

There could be a suggestion of using render instead of redirect_to, but I'm using Devise, so I would like to hand over the functionality to Devise, instead of manually doing it all by myself.

There is another idea of using cookies to store the email address, but I'm interested in more of a Rails way.

Upvotes: 1

Views: 216

Answers (2)

Eyeslandic
Eyeslandic

Reputation: 14910

You can use the flash for this

flash[:email] = params[:email]
redirect_to new_user_registration_path

in your view, something like this

<%= hidden_field_tag :email, flash[:email]

You will need to add this line

class ApplicationController < ActionController::Base
  add_flash_types :email

I'm just posting this as a possible solution, I realize this is not some best-practice solution for every case

Upvotes: 1

Anand
Anand

Reputation: 6531

There can be another way too, one way is to using session

On the first step of form submission store email in session variable and use it on the further step and after that clear that session variable.

Eg -

def first_step
  @user = User.new
end

def second_step
  # Assuming after first step form is being submitted to second step
  session[:email] = params[:email]
end

def next_step
  user_email = session[:email]
end

Hereby session[:email] will be available everywhere except model layer unless it is set to blank (session[:email] = nil), that should be set to blank after the user is created.

Upvotes: 3

Related Questions