Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friendly_id slug not changing on update

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!

like image 619
Tallboy Avatar asked Sep 28 '13 22:09

Tallboy


2 Answers

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.

like image 77
AJcodez Avatar answered Oct 21 '22 13:10

AJcodez


more exactly, you should use self.title_changed?

def should_generate_new_friendly_id?
  slug.blank? || self.title_changed?
end
like image 29
Tan Nguyen Avatar answered Oct 21 '22 14:10

Tan Nguyen