如何在Rails路径中声明范围?

时间:2015-07-05 10:16:37

标签: ruby-on-rails ruby-on-rails-4 routes scope rails-routing

我有一个文章资源,它被定义为一个平面资源,但也是一个作用于变量用户的资源:

resources :articles
scope ':user' do
  resources :articles
end

在这种情况下,article_path 123会生成/articles/123。如何生成范围路径,例如/mary/articles/123?例如,article_path 123, user: 'mary'不起作用;它只是添加了?user=mary

rails routes表示范围路径没有特殊名称:

article_path    GET /articles/:id(.:format) articles#show
                ...
                GET /:user/articles(.:format) articles#index

1 个答案:

答案 0 :(得分:3)

尝试添加as以创建路线助手

scope ':user', as: 'user' do
  resources :articles
end

你会得到

user_articles_path(user, article)

同时检查routing