I have a controller set as the root of my app. It accepts in a parameter called uid and checks to see if the user exists. If not, I want it to redirect to the new user page and pre-populate the uid field with the uid in the parameter.
In my root_controller:
def index
if params[:uid]
@user = User.find_by_uid(params[:uid])
if ([email protected]?)
# do some stuff
else
session[:user_id] = params[:uid]
redirect_to(new_user_path, :notice => 'Please register as a new user')
end
else
# error handling
end
end
In my users_controller, GET /users/new action:
def new
@user = User.new
@user.uid = session[:user_id]
# standard respond_to stuff here
end
This all works fine, but is this an acceptable way to do this? I originally tried passing the uid in the redirect statement, like:
redirect_to(new_user_path, :notice => 'Please register as a new user', :uid => params[:uid])
or even testing it with:
redirect_to(new_user_path, :notice => 'Please register as a new user', :uid => 'ABCD')
but neither seemed to pass the value to users_controller...I couldn't access it using params[:uid] from that controller.
Is session a proper place to store stuff like this, or is there a better way to pass it via the redirect? Thanks!
A session is fine to store that kind of information. Depending on what you are doing with the uid
it might actually be dangerous to allow it to be read from the URL. Imagine if the end user was malicious and started putting other user's IDs into there.
For messages that should only last until the next request Rails actually has the flash
object which will carry it over for you.
http://guides.rubyonrails.org/action_controller_overview.html#the-flash
That said, if you want to redirect to a url and pass some params, do so like this:
redirect_to(new_user_path(:notice => 'Please register as a new user', :uid => 'ABCD'))
The params you want to pass are arguments to the new_user_path
method, not the redirect_to
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With