【发布时间】:2014-04-30 13:01:43
【问题描述】:
在 Rails 4.1 应用程序中,我创建了一组路由,以避免在这种类型的关系中严重嵌套:
User has_and_belongs_to_many :blogs, join_table: 'blogs_users'
User has_many :posts, through: :blogs
Blogs has_and_belongs_to_many :users, join_table: 'blogs_users'
Blogs has_many :posts
Posts has_and_belongs_to_many :tags, join_table: 'tags_posts'
Posts has_and_belongs_to_many :categories, join_table: 'categories_posts'
Posts has_many :comments
Posts belongs_to :user
Posts belongs_to :blogs
Comments belongs_to :posts
这很简单,但死记硬背看起来如何(我被告知这更容易):
namespace :api do
namespace :v1 do
resource :users, only: [:index, :show] do
resource :blogs, only: [:index, :show]
end
resource :blogs, only: [:index, :show] do
resource :posts, only: [:index, :show]
end
resource :posts, only: [:index, :show] do
resource :tags
resource :comments
resource :categories
end
end
end
rake routes 命令吐出:
Prefix Verb URI Pattern Controller#Action
api_v1_users_blogs GET /api/v1/users/blogs(.:format) api/v1/blogs#show
api_v1_users GET /api/v1/users(.:format) api/v1/users#show
api_v1_blogs_posts GET /api/v1/blogs/posts(.:format) api/v1/posts#show
api_v1_blogs GET /api/v1/blogs(.:format) api/v1/blogs#show
api_v1_posts_tags POST /api/v1/posts/tags(.:format) api/v1/tags#create
# This is just a few to keep the post clean and manageable. I can gist the whole output if you require it.
如您所见,我缺少id 和index 我确信我的错误是初级的,但是我对什么迷失了......
我还担心访问 api 的用户将如何创建帖子,因为我只进行 API 密钥身份验证。我的意思是我想我可以创建一个“current_user”,基于它在创建帖子时将用户 ID 传递给帖子。
我的问题是:
- 我的 ID 和索引在哪里?
- 对于显示的关系类型,我的嵌套级别(在路由中)是否合适?
【问题讨论】:
标签: ruby-on-rails routes nested-routes