views:

108

answers:

2

I have a named route like the following:

map.with_options :path_prefix => '/:username', :controller => 'questions' do |q|
    q.question '/:id', :action => 'show', :conditions => { :method => :get }
end

Now to generate a URL to a specific question I have to write

question_path( :id => @question.id, :username => @question.user.username )

Which is pretty cumbersome. I would like to be able to write

question_path(@question)
# or even
link_to 'Question', @question

and get the desired result.

How is this possible? I assume I have to overwrite the default helper to achieve this.

A: 

It seams like you want a nested route for users/question.

map.resource :users do |user|
  map.resources :question, :shallow => true
end

This way, you have access to the user questions with /users/1/questions, but you can still access /questions/1 to a specific question.

robertokl
The thing is, my URL looks like :username/:question_id and I think it doesn't work for that. Would the solution you suggested even facilitate the URL generation?
Philipe Fatio
Why you need this url like? Is this a customer request?If not, I highly recommend using the convention for routes in rails that would be, in your example, something like /users/:user_id/questions/:id
robertokl
I want it in this format, because /users/:user_id/questions/:id is just too long and I'm even showing the title slug after the id so something like: `/john/425-whats-going-on`
Philipe Fatio
A: 

You can use question_path(@question.user.username, @question)

Or you can write helper method:

  def user_question_path(question)
    question_path(question.user.username, question)
  end

And use user_question_path(@question)

Voyta