简体   繁体   中英

Rails complex routing, easier named routes helpers

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM