【问题标题】:Rails :: Generate slugs with FriendlyId, Globalize and slug_candidatesRails :: 使用 FriendlyId、Globalize 和 slug_candidates 生成 slug
【发布时间】:2016-09-26 16:18:47
【问题描述】:

我正在构建一个 Rails 应用程序,但在为定义了第二个语言环境的文章生成 slug 时卡住了。
对于主要语言环境(法语),它检查文章是否已经有标题,如果是这样,则在末尾添加一个整数(id),但对于第二语言环境(英语),它只是生成 slug 而不检查文章是否存在(这给了我重复的蛞蝓)。

这是我的模型

class Post < ActiveRecord::Base
  translates :title, :slug, :content, fallbacks_for_empty_translations: true 
  active_admin_translates :title, :slug, :content, fallbacks_for_empty_translations: true 

  extend FriendlyId 
  friendly_id :slug_candidates, use: [:slugged, :globalize, :finders]

  private

  def slug_candidates
    [:title, [:title, :deduced_id]] # works for main locale but not others
  end

  def deduced_id
    self.class.where(title: title).count + 1
  end
end

当文章已经存在具有相同标题时,如何将 id 添加到辅助语言环境的 slug 中?

感谢您的帮助!

我的项目

  • Rails 4.2.6
  • ActiveAdmin 1.0.0.pre2
  • 全球化 5.0.1
  • FriendlyId 5.1.0
  • FriendlyId-globalize 1.0.0.alpha2

【问题讨论】:

    标签: ruby-on-rails friendly-id globalize


    【解决方案1】:

    我终于可以像这样更新 slug_candidates 方法了:

    def slug_candidates
      [[:title, :deduced_id]]
    end
    

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2013-09-11
      • 2018-03-11
      • 2014-11-19
      • 2012-06-02
      • 2011-10-15
      • 1970-01-01
      • 2013-03-20
      • 2018-09-25
      相关资源
      最近更新 更多