【问题标题】:friendly_id and acts_as_paranoid creating duplicate slugsfriendly_id 和acts_as_paranoid 创建重复的蛞蝓
【发布时间】:2014-03-12 19:27:44
【问题描述】:

我目前在模型上使用acts_as_paranoid 和friendly_id (5.0.1),当我销毁模型并尝试创建一个新模型时,它会生成与我得到的相同的slug:

ERROR:  duplicate key value violates unique constraint "index_papers_on_slug"

我需要以某种方式获取检查 slug 是否已经存在的代码,检查所有对象的范围,而不仅仅是未删除的对象。

在检查蛞蝓是否已经存在时,我怎样才能让friendly_id 使用with_deleted。我应该注意,我也在使用 slug 历史,这可能会使事情进一步复杂化。

深入挖掘后,我意识到,由于我使用的是历史记录,所以当对象只是被软删除时,slug 将被完全删除:

DELETE FROM "friendly_id_slugs" WHERE "friendly_id_slugs"."id" = $1  [["id", 9423]]

所以,我只需要弄清楚如何防止这种情况发生,我应该没问题,因为在尝试查找有效 slug 时,friendly_id 代码本身似乎已经在使用unscoped

【问题讨论】:

    标签: ruby-on-rails friendly-id acts-as-paranoid


    【解决方案1】:

    Friendly_id 有一个名为 scoped 的模块,它允许您在一个范围内生成独特的 slug。所以,大概

    class Paper < ActiveRecord::Base
      extend FriendlyId
      friendly_id :title, :use => :scoped, :scope => :unscoped
    end
    

    会解决问题。

    【讨论】:

    • 这会导致以下错误:undefined method unscoped for Paper
    • 嗯,您可以尝试在其中创建一个调用unscoped 的包装器作用域吗?
    • 问题似乎是friendly_id 范围期望在对象的其他属性上限定范围,而不一定设置搜索范围,所以当我创建一个新方法时,它会抱怨 unscoped 列不存在。
    【解决方案2】:

    将以下内容添加到模型中允许我覆盖 slug 上的依赖销毁

    def has_many_dependent_for_slugs; end
    

    解决方案来自对此github issue的评论。

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 2013-02-02
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2012-03-31
      • 2011-05-20
      • 2012-09-30
      相关资源
      最近更新 更多