友好 ID slug 不包含 id [英] Friendly ID slug does not contain the id

查看:36
本文介绍了友好 ID slug 不包含 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的网址:

http://domain.com/products/454-table-lamp

所以我像这样使用friendly_id:

So I use friendly_id like so:

extend FriendlyId

friendly_id :slug_candidates, use: :history

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

现在,由于友好的 id 在保存对象之前生成了 slug,我最终会得到一个像这样的 url(请注意 URL 中缺少的 id):

Now, since friendly id generates the slug before the object is saved I end up with an url like so (Please note the missing id in the URL):

http://domain.com/products/table-lamp

现在虽然这还不算太糟糕.一旦我保存了另一个名为台灯"的产品,我就会得到一个这样的 URL:

Now while this is not too bad as such. As soon as I save another Product called "Table Lamp", I will get an URL like this:

http://domain.com/products/table-lamp-ebaf4bf5-a6fb-4824-9a07-bdda34f56973

所以我的问题是,我如何确保友好 ID 也会创建包含该 ID 的 slug.

So my question is, how can I make sure, friendly ID creates the slug containing the ID as well.

推荐答案

只需将 after_commit 回调添加到您的模型中即可.在此回调中,将 slug 设置为 nil 并保存:

Just add an after_commit callback to your model. In this callback, set slug to nil and save:

  after_commit :update_slug, on: :create

  def update_slug
    unless slug.include? self.id.to_s
      self.slug = nil
      self.save
    end
  end

这篇关于友好 ID slug 不包含 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆