Rails 4 Friendly Id Slug Not Updating

前端 未结 2 1763
情话喂你
情话喂你 2021-02-12 07:13

I\'m using the following:

gem \'friendly_id\', github: \'FriendlyId/friendly_id\', branch: \'master\'

I am creating an Article section on my Ra

2条回答
  •  無奈伤痛
    2021-02-12 07:52

    In FriendlyId 4 (Rails 3 compatible) there was a method

    should_generate_new_friendly_id?
    

    and you could define it on your model to control when slug is regenerated. Try

    def should_generate_new_friendly_id?
      name_changed?
    end
    

    to regenerate slug when name changes.

    EDIT

    FriendlyId version 5 (Rails 4 compatible) doesn't regenerate slugs on save anymore. To restore this functionality you can either set slug column to nil before saving or use the solution provided above.

    EDIT 2

    You need to override the slug setter for your saves to work for Rails <5 & FriendlyId > 5 as referenced in this issue.

    Add this to the model file

      def slug=(value)
        if value.present?
          write_attribute(:slug, value)
        end
      end
    

提交回复
热议问题