1
我有一個小的Rails 5應用程序有板,並且每個董事會都有帖子(有點像Reddit)。Rails嵌套的資源ID是不是相對於父母
主板型號:
class Board < ApplicationRecord
has_many :posts
end
Post模型:
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是相對於母板?