【问题标题】:Routes not looking right. Missing id and index路线看起来不正确。缺少 id 和索引
【发布时间】: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.

如您所见,我缺少idindex 我确信我的错误是初级的,但是我对什么迷失了......

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

我的问题是:

  • 我的 ID 和索引在哪里?
  • 对于显示的关系类型,我的嵌套级别(在路由中)是否合适?

【问题讨论】:

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


    【解决方案1】:

    您应该将resource 替换为resources

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

    See documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 2023-03-18
      • 2021-09-22
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多