在路由中没有父ID的嵌套资源

时间:2012-06-16 17:29:10

标签: ruby-on-rails-3 routes nested-resources

我有两个资源:

resources :users do
 resources :cars
end

该协会是:

  • 用户可以拥有多辆车
  • 汽车属于用户

在进行这种嵌套资源时,我得到的网址如下:

/users/:id/cars/new 

我的问题是:

如果仅仅/cars/new(没有/ users /:id)更有意义,因为我从登录的current_user获得:id,我将如何在路由中解决这个问题? / p>

3 个答案:

答案 0 :(得分:3)

我根本不会使用嵌套路线。您可以拥有嵌套模型,而无需嵌套路由。只需从会话中加载当前用户(您可能已经这样做了),并确保没有人可以访问汽车控制器,除非他们已登录。

答案 1 :(得分:3)

这个问题的正确答案是:

resources :users do
  collection do
    resources :cars
  end
end

答案 2 :(得分:0)

在routes.rb

resources :cars, :only => [:new, :create] # if you don't need all actions
resources :users do
  resources :cars
end

在汽车控制器中类似

before_filter :find_user
...
private
def find_user
  @user = params[:user_id] ? User.find(params[:user_id]) : current_user
end