Denis Denis - 4 months ago 14
Ruby Question

How to modify Rails path names dynamically?

My

params[:type]
equals
item
(singular)

I need to send the user to

items_path(name: params[:name])


I need to pluralize the
params[:type]
part of the path and merge it with my view to get my link right, and I'm struggling to do that.

Answer

It depends. For unconditional pluralization you can do this:

plural = params[:type].pluralize # => 'items'
route_method = "#{plural}_path" # => 'items_path'
public_send(route_method, name: params[:name])

But it doesn't seem a very safe solution to me. Taking user input and executing it like that always rings a bell in my head. Perhaps, some whitelisting would be better (more readable too)

path = case params[:type]
  when 'item'
    items_path(name: params[:name])
  when 'foobar'
    foobars_path
  else
    fail 'Unknown type'
end