【发布时间】:2019-03-14 15:06:14
【问题描述】:
我正在使用 friendly_id 将自定义 slug 添加到我的模型及其相应的 url。目前我有一个Post 属于Board 的设置。毫无疑问,在某些情况下,帖子的标题与另一个帖子的标题相同,但来自不同的董事会。我经常注意到网站(包括 SO)在 slug 之前添加了一组唯一的数字,以确保没有唯一性问题:
https://stackoverflow.com/questions/123456/my-example-question
我想知道实现这一目标的最佳方法是什么?这不能仅通过路由文件完成,因为仍然存在创建两个或多个相同帖子的可能性。是否会同时更改我的模型、路由文件和friendly_id gem 的配置?
我的最终目标是为我的帖子生成一个这样的网址:
https://example.com/boards/example-board/123456/example-post
class Board < ApplicationRecord
extend FriendlyId
has_many :posts
friendly_id :name, use: :slugged
end
class Post < ApplicationRecord
extend FriendlyId
belongs_to :board
friendly_id :title, use: :slugged
end
resources :boards do
scope module: :boards do
resources :posts
end
end
【问题讨论】:
标签: ruby-on-rails routing friendly-id