james
james

Reputation: 4049

How to send data from one model/ controller to another in Rails

Not sure how to achieve this:

  1. User enters email on page 1
  2. On page 2, User doesn't have to enter email again, because it has persisted (again across controllers/ models)

Yet another way of saying it using code snippets below:

  1. User enters email "[email protected]" in signups/new
  2. Email is posted to signups/create, so now the model signups has one new row of data with "[email protected]"
  3. User redirected to requests/new
  4. On requests/new, I'd like the same email that the user just signed up with to be immediately accessible, i.e., @requestrecord.email = "[email protected]" in the new action, so User doesn't have to re-enter it and post to requests/create

Signup Controller code

def new
    @signup = Signup.new
end

def create
    @signup = Signup.new(signup_params)
    if @signup.save
        redirect_to new_request_path
    else
        render new_signup_path
    end

end

Request Controller code

def new
    @requestrecord = Request.new
end

def create
    @requestrecord = Request.new(request_params)
end

Upvotes: 1

Views: 397

Answers (1)

tirdadc
tirdadc

Reputation: 4703

You could just set the user's email in a session variable:

def create
  @signup = Signup.new(signup_params)
  if @signup.save
      session[:user_email] = @signup.email
      redirect_to new_request_path
  else
      render new_signup_path
  end
end

and then you can use it as needed with session[:user_email] in your Request controller.

Upvotes: 1

Related Questions