路线不正确。缺少id和索引

时间:2014-04-30 13:01:43

标签: ruby-on-rails routes nested-routes

在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.

正如您所看到的那样,我错过了idindex我确信我的错误是不成熟的我怎么会迷失方向......

我还担心访问api的用户将如何创建帖子,因为我只进行API密钥身份验证。我的意思是我想我可以创建一个" current_user"基于该用途,用于将用户ID传递给帖子,当创建一个时。

我的问题是:

  • 我的ID和索引在哪里?
  • 我的关系类型的嵌套(在路由中)是否合适?

1 个答案:

答案 0 :(得分:4)

您应该将resource替换为resources

复数有很多意义:可能有很多,因此需要id,索引的存在等......

See documentation