简体   繁体   English

Rails复杂的路由,更容易命名的路由助手

[英]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 现在要生成指向特定问题的URL,我必须写

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. 这样,您可以使用/ users / 1 / questions访问用户问题,但是仍然可以访问/ questions / 1特定问题。

You can use question_path(@question.user.username, @question) 您可以使用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) 并使用user_question_path(@question)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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