【问题标题】:Rails complex routing, easier named routes helpersRails 复杂路由,更简单的命名路由助手
【发布时间】:2010-06-02 18:05:00
【问题描述】:

我有一个命名路线,如下所示:

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

现在要生成一个指向我必须编写的特定问题的 URL

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

这很麻烦。我希望能够写作

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

并得到想要的结果。

这怎么可能?我假设我必须覆盖默认帮助程序才能实现这一点。

【问题讨论】:

    标签: ruby-on-rails routing helper


    【解决方案1】:

    您可以使用question_path(@question.user.username, @question)

    或者你可以编写辅助方法:

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

    并使用user_question_path(@question)

    【讨论】:

      【解决方案2】:

      看起来你想要一个用户/问题的嵌套路由。

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

      这样,您可以通过 /users/1/questions 访问用户问题,但您仍然可以访问 /questions/1 来解决特定问题。

      【讨论】:

      • 问题是,我的 URL 看起来像 :username/:question_id ,我认为它不起作用。您建议的解决方案是否会促进 URL 生成?
      • 为什么需要这个网址?这是客户要求吗?如果没有,我强烈建议使用 Rails 中的路线约定,在您的示例中,类似于 /users/:user_id/questions/:id
      • 我想要这种格式,因为 /users/:user_id/questions/:id 太长了,我什至在 id 之后显示标题段,例如:/john/425-whats-going-on
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多