在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传递给帖子,当创建一个时。
我的问题是: