2012-04-27 85 views
2

我知道如何用match来做到这一点,但我真的想在资源块中做到这一点。下面是我所(简化):Rails路由:覆盖资源/成员块中的操作名称

resources :stories do 
    member do 
    'put' collaborator 
    'delete' collaborator 
    end 
end 

我正在寻找一种方式,让在URL相同的动作名称,但必须在控制不同的入口点。目前,我有我的控制器:

# PUT /stories/1/collaborator.json 
def add_collaborator 
    ... 
end 

# DELETE /stories/1/collaborator.json 
def remove_collaborator 
    ... 
end 

所以,我想这一点:

resources :stories do 
    member do 
    'put' collaborator, :action => 'add_collaborator' 
    'delete' collaborator, :action => 'remove_collaborator' 
    end 
end 

但这似乎并没有在工作的时候我写了一个RSpec的单元测试:

describe "PUT /stories/1/collaborator.json" do 
    it "adds a collaborator to the story" do 
    story = FactoryGirl.create :story 
    collaborator = FactoryGirl.create :user 

    xhr :put, :collaborator, :id => story.id, :collaborator_id => collaborator.id 

    # shoulds go here... 
end 

我得到这个错误:

Finished in 0.23594 seconds 
5 examples, 1 failure, 1 pending 

Failed examples: 

rspec ./spec/controllers/stories_controller_spec.rb:78 # StoriesController PUT  
    /stories/1/collaborator.json adds a collaborator to the story 

我假设这个错误是因为我试图定义我的路线的方式是不正确的......任何建议?

回答

2

以下更好吗?

resources :stories do 
member do 
    put 'collaborator' => 'controller_name#add_collaborator' 
    delete 'collaborator' => 'controller_name#remove_collaborator' 
end 
end 

你也应该在终端开展检查路线:

$ rake routes > routes.txt 

并打开生成的文件routes.txt看到从你的routes.rb文件中生成什么路线。

+0

这使得路由显示在rake路由输出中正确显示,为此我永远感激:)我仍然得到rspec失败,但现在至少我知道这不是我的路由被破坏。谢谢! – jaydel 2012-04-27 16:10:05

+0

您的欢迎,也许我可以帮助您进一步与您的rspec失败? – Kulgar 2012-04-27 16:15:03

+0

那真是太棒了。我尝试使用get路径做一个更简单的例子,并将其命名为:path。从浏览器它完全可以工作。当我执行'xhr:get,:test_path'时,它找不到路由,它的基本信息和我原来的帖子中一样。 – jaydel 2012-04-27 16:17:09