Home > database >  Rails 7: How to pass a variable from one controller to the next
Rails 7: How to pass a variable from one controller to the next

Time:04-29

In Rails, it used to be possible to pass a variable (here: :anchor) from one controller to the next, by calling something like:

redirect_to user_profile_path(anchor: 'details')

But trying to catch :anchor in the next controller, i.e. like so...

puts params[:anchor].inspect
puts request.params[:anchor].inspect

...fails. Why?

(I'm on Rails 7, in case it matters.)

EDIT:

Strangely enough, when I use a different key, i.e. test...

redirect_to user_profile_path(anchor: 'details', test: 'test-value')

...then...

puts params[:test].inspect

...correctly returns the value, in the log file:

'test-value'

CodePudding user response:

This really has very little to do with Rails and more with how browsers and URI's work.

Anchor is a special option for url_for for that adds a URI Fragment (aka anchor or hash) to the URL.

Clients do not send the URI fragment to the server when requesting a URI. Its transparent to the server by design. But the client will accept the fragment from the server.

If you want to pass additional information from the client to the server in a GET request you need to do it either by adding a query string parameter, custom headers or a cookie.

Using user_profile_path(anchor: 'details', test: 'test-value') works since test: is not a named option and will instead add a query string parameter.

  • Related