BookOfGreg
BookOfGreg

Reputation: 3706

Redirect_to with string path

I'm trying to redirect to a location based on a param on a submitted form. If params[:route] = group , I want to redirect to groups_path. I tried the following method to redirect but obviously enough the groups_path is a variable and not a string. How can I redirect based off the param?

redirect_to "#{params[:route]}s_path"

Edit: realised I can redirect to the actual path but this doesn't seem like a very rails way of doing it.

redirect_to "/#{params[:route]}s"

Upvotes: 8

Views: 5347

Answers (2)

jibiel
jibiel

Reputation: 8303

redirect_to send("#{params[:route].pluralize}_path")

But I'd rather write a wrapper-helper returning appropriate url helper based on the params[:route] value. params[:route] could potentially have any value and you may want to rescue in these cases.

Upvotes: 14

Michal Macejko
Michal Macejko

Reputation: 370

send can calls private method, therefore better is public_send

and instead "#{params[:route]}s" use "#{params[:route].pluralize}

redirect_to public_send("#{params[:route].pluralize}_path")

Upvotes: 2

Related Questions