【问题标题】:FriendlyId doesn't update slug on title changedFriendlyId 不会在标题更改时更新 slug
【发布时间】:2016-10-18 07:58:19
【问题描述】:

我正在使用 ActiveAdmin、Globalize 和 FriendlyId 构建 Rails 应用程序。

在我的模型中,我设置了 Globalize 和 FriendlyId 参数(摘录):

class Post < ActiveRecord::Base
  translates :title, :slug, :content
  active_admin_translates :title, :slug, :content do
    validates :title, presence: true
  end

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

  private

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

  # Used to add prefix number if slug already exists
  def deduced_id
    count = Post.where(title: title).count
    return count + 1 unless count == 0
  end
end

但是,当我在 ActiveAdmin 中更新文章标题时,slug 永远不会由friendly_id 更新,所以我添加了这个方法:

def should_generate_new_friendly_id?
   title_changed? || super
end

当我这样做时,title_changed?始终为 false,因为我不知道新标题未发送到模型的原因,但对于未翻译的其他参数,它们被正确获取。

例如:

logger.debug(title) # => Give me new updated title value BUT
title_changed? # => Always nil
online_changed? # => Works

模型怎么可能不知道翻译属性的更新?
我错过了什么?

感谢您的帮助!

我的项目

  • Rails 4.2.7.1 / Ruby 2.3.0
  • ActiveAdmin 1.0.0pre4
  • 全球化 5.0.1
  • FriendlyId 5.1.0
  • FriendlyId 全球化 1.0.0.alpha2

编辑:(我的表单的摘录)

f.translated_inputs 'Translated fields', switch_locale: true do |t|
    t.input :title
    t.input :content
end

【问题讨论】:

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


    【解决方案1】:

    但是当你在 ActiveAdmin 中保存模型时,如果你在表单中有一个 slug 字段并且感觉不到它,那么将包含空字符串并且不会生成 slug。 如何解决?像这样覆盖模型中的 slug setter 方法:

     def should_generate_new_friendly_id?
        slug.blank? || title_changed?
     end
    
    
    
       def slug=(value)
        if value.present?
          write_attribute(:slug, value)
        end
      end
    

    试试这个

    【讨论】:

    • 谢谢,但我的表单中没有任何“slug”输入字段(我编辑了我的问题,添加了表单提取)。当我创建一个新帖子时,所有语言都正确设置了 slug。
    猜你喜欢
    • 2016-09-24
    • 1970-01-01
    • 2018-03-11
    • 2020-06-17
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2018-02-20
    • 2013-03-20
    相关资源
    最近更新 更多