Rails 嵌套资源 ID 不相对于父级



我有一个有板的小型 Rails 5 应用程序,每个板都有帖子(有点像 Reddit)。

板型号:

class Board < ApplicationRecord
has_many :posts
end

帖子模型:

class Post < ApplicationRecord
belongs_to :board
validates :title, presence: true, length: { minimum: 1, maximum: 64}
mount_uploader :image, ImageUploader
end

我已将帖子资源嵌套在董事会资源下。

routes.rb:

Rails.application.routes.draw do
resources :boards, param: :name, path: '/' do
resources :posts, path: '/', except: [:index]
end
end

铁路路线:

Prefix Verb   URI Pattern                     Controller#Action
board_posts POST   /:board_name(.:format)          posts#create
new_board_post GET    /:board_name/new(.:format)      posts#new
edit_board_post GET    /:board_name/:id/edit(.:format) posts#edit
board_post GET    /:board_name/:id(.:format)      posts#show
PATCH  /:board_name/:id(.:format)      posts#update
PUT    /:board_name/:id(.:format)      posts#update
DELETE /:board_name/:id(.:format)      posts#destroy
boards GET    /                               boards#index
POST   /                               boards#create
new_board GET    /new(.:format)                  boards#new
edit_board GET    /:name/edit(.:format)           boards#edit
board GET    /:name(.:format)                boards#show
PATCH  /:name(.:format)                boards#update
PUT    /:name(.:format)                boards#update
DELETE /:name(.:format)                boards#destroy

我遇到的问题是帖子 ID 是全局递增的,而不是相对于它发布的板。举个例子:

假设我有两个空板:"新闻"板和一个"政治"板。我为新闻板创建了一个帖子并获取路线:http://localhost:3000/news/1.太好了,这就是我所期望的。它是板上的帖子 #1,因此帖子 ID 应为 1。现在我的问题是,如果我向另一个板发帖,该帖子将获得 ID 2,如:http://localhost:3000/politics/2.我希望它是http://localhost:3000/politics/1的,因为它是相对于该板的第一篇文章。

我怎样才能实现这一点,以便 ID 相对于父主板?

我的提示:不要这样做,这很容易出错。

但是如果你真的需要这个,你可以使用这样的代码:

Board.find_by(name: params[:board_name]).posts.first(id).last

请记住,它会将与给定讨论区相关的所有帖子加载到内存中,因此如果您的讨论区有数百万个帖子,则性能可能是一个问题。

最新更新