【发布时间】:2023-04-03 06:38:01
【问题描述】:
我正在构建一个托管游戏的 Rails 应用程序。游戏属于类别,因此每个类别可以有许多游戏。
我正在使用 Friendly_id gem 生成 URL slugs 并具有以下设置:
类别.rb
class Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name_and_games, use: [:slugged]
has_many :games
def name_and_games
"#{name}-games"
end
end
Games_Controller.rb
...
def category
@category = Category.friendly.find(params[:id])
@categories = Category.all
@games = @category.games.page(params[:page])
render 'games/index'
end
...
Routes.rb
get ':friendly_id', to: "games#category", as: :category
Category_View.html.erb
<% categories.each do |category| %>
<%= link_to category_path(category) do %>
<span><%= pluralize(category.name.capitalize, "Game") %> (<%= category.games.count %>)</span>
<% end %>
<% end %>
问题是,当我使用 Friendly_id 的 slugged 模块时,Rails 生成的网址没有“-games”后缀,所以我最终得到这样的网址:
http://localhost:3000/action
http://localhost:3000/adventure
有什么方法可以让 rails 将“-games”保留在我的 URL 中,并让它们很好地发挥作用,以便在模型中进行处理时删除“-games”?
谢谢。
【问题讨论】:
-
看起来 has_permalinks gem 在解决这种情况方面比 Friendly_id 做得更好。不过,如果能与 Friendly_id 一起使用会很好,因为它似乎是更好的支持选项,而且它还有更多我想利用的功能。
标签: ruby-on-rails-4 seo friendly-id