【问题标题】:Friendly ID for duplicates重复的友好 ID
【发布时间】:2015-03-11 04:11:05
【问题描述】:

假设我们有 2 个标题相同的帖子:“超级英雄”。第一篇文章应该有 url superheros-alternative-1,第二个应该有 superheros-alternative-2。 问题是,当我更新其中一篇文章的标题时,它们的 url 都应该改变。我的意思是如果我将标题更改为“奇迹”,那么网址应该变成以下 奇迹替代 1 和奇迹替代 2。 现在我有了下一个代码

class Post < ActiveRecord::Base

  before_update :update_slug

  def should_generate_new_friendly_id?
    slug.blank? || title_changed?
  end

  def update_slug
    title = Post.find(self.id).title
    Post.where(title:title).each do |post|
      post.update_column(:title,self.title)
    end
  end
end

【问题讨论】:

  • 那么,您的问题到底是什么?您的帖子中没有。
  • 抱歉,问题是 - “当我们更新其标题时,如何更新主页及其副本的 URL?”

标签: ruby-on-rails ruby friendly-url slug friendly-id


【解决方案1】:

您不应为此使用update_column because it will not trigger the callbacks, validations and such,因此friendly_id 不会更新您的slug。更新模型对象属性并改为调用.save

此外,您可以在更新常规记录后更新其他记录(在after_save 回调中)-在那里您将可以访问原始标题和新标题,而无需额外执行Post.find(self.id)

【讨论】:

  • 是的,你是对的,update_column不会调用回调。您可能是对的,更好的解决方案是在控制器而不是模型中进行此操作。非常感谢!
  • @ArtemGalas 我的意思是after_save ActiveRecord callback in the model,而不是在控制器中。 ;)
猜你喜欢
  • 1970-01-01
  • 2013-06-19
  • 2016-05-15
  • 2014-09-17
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多