【问题标题】:Rails DESTROY action on nested resource without IDRails DESTROY 对没有 ID 的嵌套资源的操作
【发布时间】:2014-06-27 18:42:49
【问题描述】:

我在routes.rb 文件中设置了以下资源:

namespace :api, path: '/', defaults: { format: 'json' }, constraints: { subdomain: 'api' } do
  namespace :v1 do
    resources :yums do
      resources :likes,  only: [:create, :destroy, :index] do
        match '/', to: 'likes#destroy', via: 'delete'
      end
    end
  end
end

我还编写了一个规范来测试我的请求:

describe "Like API requests" do
  before (:each) do 
    host! 'api.example.com'

    @user = FactoryGirl.create(:user)
    @other_user = FactoryGirl.create(:user)
    @yum = FactoryGirl.create(:yum, user: @other_user)
  end

  describe "liking a Yum" do
    it "should increase the Yum's Like count" do
      expect do
        post "/v1/yums/#{@yum.id}/likes", { authorization: token_header(@user.auth_token) }
      end.to change(@yum.reload.likes, :count).by(1)
    end
  end

  describe "unliking a Yum" do
    it "should increase the Yum's Like count" do
      expect do
        delete "/v1/yums/#{@yum.id}/likes", { authorization: token_header(@user.auth_token) }
      end.to change(@yum.reload.likes, :count).by(-1)
    end
  end
end

我希望 Likes 控制器不需要 ID 来执行销毁操作,因为我在我的用户模型上使用方法来喜欢和不喜欢,但这个方案似乎不起作用,我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby routing resources


    【解决方案1】:

    尝试在您的 routes.rb 中添加一条路线,例如:

    match "v1/yums/:yum_id/likes", to: "likes#destroy", via: "delete", defaults: { id: nil }
    

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 2017-01-10
      相关资源
      最近更新 更多