我试图从Post模型创建API端点。它应该能够阅读,更新,删除和创建帖子。
但是帖子需要与主题相关联才能创建它,所以我将它嵌套在主题下。这是我的路线
namespace :api do
namespace :v1 do
resources :users, only: [:index, :show, :create, :update]
resources :posts, only: [:show, :update, :destroy]
resources :topics, except: [:edit, :new] do
resources :posts, only: [:create]
end
end
end
api_v1_post GET /api/v1/posts/:id(.:format) api/v1/posts#show
PATCH /api/v1/posts/:id(.:format) api/v1/posts#update
PUT /api/v1/posts/:id(.:format) api/v1/posts#update
DELETE /api/v1/posts/:id(.:format) api/v1/posts#destroy
api_v1_topic_posts POST /api/v1/topics/:topic_id/posts(.:format) api/v1/posts#create
api_v1_topics GET /api/v1/topics(.:format) api/v1/topics#index
POST /api/v1/topics(.:format) api/v1/topics#create
api_v1_topic GET /api/v1/topics/:id(.:format) api/v1/topics#show
PATCH /api/v1/topics/:id(.:format) api/v1/topics#update
PUT /api/v1/topics/:id(.:format) api/v1/topics#update
DELETE /api/v1/topics/:id(.:format) api/v1/topics#destroy
我的问题是我得到一个"没有路线匹配"我运行Rspec时出错
答案 0 :(得分:1)
我认为问题在于关系。
请添加Topic
和Post
之间的关系,然后尝试。
class Topic < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :topic
end
答案 1 :(得分:0)
如果您尝试创建的路由POST api/v1/topics/:topic_id/create_post
转到TopicsController而不是希望嵌套看起来像这样:
resources :topics, except: [:edit, :new] do
post 'create_post' => 'topics#create_post'
end
答案 2 :(得分:0)
如果您还没有成功,请尝试创建您的路线。它应该提供你想要的输出。
resources :topics, except: [:edit, :new] do
collection do
post 'create_post'
end
end