简体   繁体   中英

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 "test@gmail.com" in signups/new
  2. Email is posted to signups/create, so now the model signups has one new row of data with "test@gmail.com"
  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, ie, @requestrecord.email = "test@gmail.com" 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM