Question

I'm using friendly_id 5.0.0.rc1, and also active_admin.

It would appear everything is working perfectly as expected, except for the fact that updating a record's slug attribute/column in active_admin does not do anything (it keeps it the same)

I find the same behavior just using console:

p = Post.first
p.slug
#=> 'test'
p.slug = 'another-test'
p.save
#=> true
p.slug
#=> 'test

My config:

FriendlyId.defaults do |config|
  config.use :reserved

  config.reserved_words = %w(admin new edit index session users register)

  config.use :finders

  config.use :slugged

  config.slug_column = 'slug'

  config.sequence_separator = '-'

  config.use Module.new {
    def should_generate_new_friendly_id?
      slug.blank? || slug_changed?
    end
  }
end

My model:

class Post < ActiveRecord::Base

  default_scope { order('created_at DESC') }

  validates :title, presence: true
  validates :body,  presence: true
  validates :views, presence: true, numericality: { only_integer: true }

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

end

my controller:

class PostsController < ApplicationController

  def index
    @posts = Post.all.page(params[:page]).per(10)
  end

  def show
    @post = Post.find_by_slug!(params[:id])

    if request.path != post_path(@post)
      redirect_to @post, :status => :moved_permanently and return
    else
      @post.increment :views if @post
    end

  end

end

Thanks!

Was it helpful?

Solution

Usually when using friendly id, you never update the slug manually. Instead:

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

And then every time you change the title, it will automatically update the slug.

OTHER TIPS

more exactly, you should use self.title_changed?

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

Incase anyone else lands here and just need to change a slug:

p = Post.first
p.slug
#=> 'test'
tmp_title = p.title
p.title = 'another-test'
p.slug = nil
p.save
#=> true
p.title = tmp_title
p.slug
#=> 'another-test'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top