2010-08-05 58 views
1

我与7个的RESTful动作加上附加的“当前的”行动,它返回第一有源FOO记录控制器:导轨3附加GET动作的RESTful控制器

class FooController < ApplicationController 

    def current 

    @user = User.find(params[:user_id]) 
    @foo = @user.foos.where(:active => true).first 

    #use the Show View 
    respond_to do |format| 
     format.html { render :template => '/foos/show' } 
    end 

    end 

    #RESTful actions 
    ... 

end 

foo的型号:belongs_to的用户模型和用户模型:has_many Foos。

如果我构造的路由这样:

resources :users do 
    resources :foos do 
    member do 
     get :current 
    end 
    end 
end 

所得路径为 '/用户/:USER_ID/FOOS /:ID'。显然,我不想指定foo:id。

我也试过:

map.current_user_foo '/users/:user_id/current_foo', :controller => 'foos', :action => 'current' 
resources :users do 
    resources :foos 
end 

得到的路线更像是我所期望的: '/用户/:USER_ID/current_foo'。

当我尝试使用这条路线,我得到一条错误:

ActiveRecord::RecordNotFound in FoosController#current 
Couldn't find Foo without an ID 

编辑

当我移动当前的行动应用控制器,一切正常。指定的路由必须与资源路由冲突。

/编辑

我缺少什么?有没有更好的路由方法?

回答

3

我想你想定义集合上的当前,而不是成员(成员是什么添加:ID)。

试试这个。

resources :users do 
    resources :foos do 
    collection do 
     get :current 
    end 
    end 
end 

这应该给你这样的路线:

current_user_foos GET /users/:user_id/foos/current(.:format)   {:controller=>"foos", :action=>"current"} 

也映射了,不再在RC中使用,它会给你一个弃用警告。

+0

有点不直观,但它的工作 - 谢谢。任何想法如何处理的情况下,如果找不到匹配的foo?我可能想要显示一个页面,指出“该人没有foo”,而不是回到最后一页并显示一条Flash消息。 – craig 2010-08-10 14:59:16

+0

嗯,很难说,用户如何选择当前的foo?你在看用户,然后点击按钮/按照链接查找分配给此用户的当前foo的?如果是这样,我会想回到请求页面,并通知说,没有发现foos会好起来的。 – Doon 2010-08-10 15:19:26