0

I have this line of code in routes.rb

get 'products#:id' => 'products#index', as: :products_hash

It works, but the problem is that the hash symbol (#) gets rendered as %23.

http://localhost:3000/products%2368

This is what it should be:

http://localhost:3000/products#68

How can I achieve this? Thanks!

hansottowirtz
  • 664
  • 1
  • 6
  • 16
  • Have you read this? http://stackoverflow.com/questions/21372675/rails-routes-slash-character-vs-hash-character – lcguida Aug 29 '14 at 20:41
  • Yes, but it doesn't really help haha – hansottowirtz Aug 29 '14 at 20:44
  • I have to ask. Why do you want to use `http://localhost:3000/products#68` instead of `http://localhost:3000/products/68`? – infused Aug 29 '14 at 20:48
  • Yeah, I'm curious about that too. =) – lcguida Aug 29 '14 at 20:49
  • Because I don't want the user to use the show action, but rather scroll to the product with id 68 in the index :) – hansottowirtz Aug 29 '14 at 20:50
  • And what about this answer: http://stackoverflow.com/a/2069190/906511 You could have the `/products/68` and in the show action redirect to index with the anchor – lcguida Aug 29 '14 at 20:54
  • 2
    I believe you should specify this manually in an `anchor` key of a `link_to` helper. It's probably impossible to specify it in routes, because routes are mostly designed to parse and select a path - and the part after a # is not part of the path. And by impossible I mean you'd need to modify rails' methods to make it work. Write a helper maybe. – D-side Aug 29 '14 at 21:15
  • 1
    You don't want this - the browser does not send what follows the # to the server at all – Frederick Cheung Aug 29 '14 at 21:52
  • This seems to work, any better ideas?: `private` `def switches_hash_path(switch)` `return switches_path(:anchor => switch.id)` `end` – hansottowirtz Aug 29 '14 at 22:01

1 Answers1

0

Rails

I feel you're missing the point of Rails' routing system, which is that you are meant to construct it around objects (hence why you call resources :controller etc).

Although I don't understand why you're defining the route you are, I'll give you some ideas. There is a "wildcard" setting for your routes in Rails, which allows you to define & pass parameters to your application out of the scope of the typical "CRUD" based applications:

#config/routes.rb
get 'products#*id' => 'products#index', as: :products_hash

This will give you the ability to send requests to the following route:

<%= link_to "Product", products_hash_path("68") %>

You'd then be able to call the param in the controller:

#app/controllers/products_controller.rb
class ProductsController < ApplicationController
   def index
      id = params[:id]
   end
end
Richard Peck
  • 76,116
  • 9
  • 93
  • 147