0

I am using Rails 4.2. In a gem, there is a route defined as

get 'book/:id', to: 'book#show', as: book

I'd like to add an additional dynamic segment in a custom route, so in the routes.rb file in my app, I have

get ':language/book/:id', to: 'book#show', as: language_book

Then in my controller, I tried to call the url helper

language_book_url language: :en, id: 3

I expect to get a url like http://host:port/en/book/3, however, instead, I get http://host:port/book/3?language=en. It seems I can't use the helper with that extra custom dynamic segment. Is it possible to get the desired path with the new dynamic segment variable? Thanks!

usmanali gave a answer in the comment, to use language_book_url :en, 3. But what if I want a mixture of dynamic segments and query string params? So my target url is http://host:port/en/book/3?barcode=1234. How can I call the url helper? A call to the helper like language_book_url('en', 3, barcode: 1234) would produce http://host:port/book/3?language=en&barcode=1234, instead of the expected one.

djiao
  • 453
  • 6
  • 11
  • try `language_book_url('en',3)` – usmanali Jun 17 '15 at 11:30
  • Yes I found that working. But how about if I want a mixture of dynamic segments and querystring params? Like I want to produce a url like http://host:port/en/book/3?barcode=123456 – djiao Jun 17 '15 at 11:37
  • you can pass the parameters then like `language_book_url('en',3, barcode: 123456)` – usmanali Jun 17 '15 at 11:50
  • so your dynamic segments are part of the arguments and the query parameters can be passed as a hash – usmanali Jun 17 '15 at 11:51
  • can you give the full route associated with the one you posted ? Only `get ':language/book/:id', 'book#show', as: language_book` if you place inside the routes.rb.. You will get an error as **ArgumentError: Missing :controller key on routes definition, please check your routes.**... – Arup Rakshit Jun 17 '15 at 11:57
  • usmanali, I tested language_book_url('en',3, barcode: 123456) and it doesn't work. It gives me `http://host:port/book/3?language=en&barcode=123456`. Strange thing is, it automatically added 'language' in the parameter so it's aware of the param name but just put it in the query string instead of the path – djiao Jun 17 '15 at 12:49

0 Answers0