2

我知道如何做到这一点,match但我真的想在资源块中做到这一点。这是我所拥有的(简化):

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

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

4

1 回答 1

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 文件生成的路由。

于 2012-04-27T16:07:24.243 回答