使用FriendlyID在Rails中独立于标题编辑slug

时间:2017-09-29 18:32:20

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

我正在创建一个Blog Rails webapp。我决定使用FriendlyID gem,我想添加在编辑视图中自定义slug的功能。然而,似乎slu子本身无法修改。目前,只有在标题运行时才会更新slug并且我希望有一个可以独立更新的slug并且不一定与标题绑定

Blog.rb

class Blog < ApplicationRecord
  enum status: { draft: 0, published: 1 }

  extend FriendlyId
  friendly_id :title, :use => [:slugged, :history]

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

blog_controller.rb

def set_blog
  @blog = Blog.friendly.find(params[:id])
end

1 个答案:

答案 0 :(得分:0)

friendly_id wiki page

中查看此帖子

假设您希望您的Blog能够独立于标题(从slug派生出来)编辑slug,并且不会默认为另一个字段:

class Blog < ActiveRecord::Base
  attr_accessor :temporary_slug
  extend FriendlyId
  friendly_id :slug, :use => [:slugged]

  def should_generate_new_friendly_id?
    temporary_slug_changed?
  end

 # track changes in non persisted attribute

  def temporary_slug=(value)
    attribute_will_change!('temporary_slug') if temporary_slug != value
    @temporary_slug = value
  end

  def temporary_slug_changed?
    changed.include?('temporary_slug')
  end

end

示例输出如下所示:

blog = Blog.create(title: "How Long is a Long Long Time")
blog.slug 
# nil
post = Blog.update_attributes(title: "Some other title", temporary_slug: "My favorite blog")
blog.slug 
# 'my-favorite-blog'

否则,如果您希望slug默认为标题版本,那么您可以这样做:

class Blog < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, :use => [:slugged]
  validates_presence_of :title

  def should_generate_new_friendly_id?
    if !slug?
      name_changed?
    else
      false
    end
  end
end

blog = Blog.create(title: "How Long is a Long Long Time", slug: 'how-long')
blog.slug 
# 'how-long'
blog = Blog.create(title: "How Long is a Long Long Time")
blog.slug 
# 'how-long-is-a-long-long-time'