Carl Edwards
Carl Edwards

Reputation: 14454

FriendlyID history not working for updated model urls in Rails

Following both FriendlyID's wiki and railscast I've tried to rewrite and redirect my urls if the name of my user model has changed. Unfortunately nothings happening. I've ran the proper migrations:

rails generate friendly_id
rails generate migration add_slug_to_artists slug:string:uniq
rake db:migrate

And applied this code as instructed but to no avail. The url remains the same after initially creating the model instance.

Artist Model

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

Users Controller

class ArtistssController < ApplicationController
  before_action :set_artist, only: [:show, :edit, :update, :destroy]

  def show
    if request.path != user_path(@artist)
      redirect_to @artist, :status => :moved_permanently
    end
  end

  def update
    if @artist.update_attributes(artist_params)
      flash[:notice] = 'Artist successfully updated'
      redirect_to @artist
    else
      render 'edit'
  end

  private
  # Use callbacks to share common setup or constraints between actions.
    def set_artist
      @artist = Artist.friendly.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def artist_params
      params.require(:artist).permit(:name)
    end
end

Upvotes: 1

Views: 450

Answers (1)

Carl Edwards
Carl Edwards

Reputation: 14454

While its stated in their docs the code for changing urls in your controller for FriendlyID 5 is never really explained. I ended up having to add @artist.slug = nil for this to take effect:

def update
  @artist.slug = nil
  if @artist.update_attributes(artist_params)
    flash[:notice] = 'Artist successfully updated'
    redirect_to @artist
  else
    render 'edit'
  end
end

Upvotes: 2

Related Questions