在FriendlyID的wiki和railscast之后,如果用户模型的名称发生了变化,我会尝试重写和重定向我的网址。不幸的是没有发生的事情。我已经进行了正确的迁移:
rails generate friendly_id
rails generate migration add_slug_to_artists slug:string:uniq
rake db:migrate
按照指示应用此代码,但无济于事。最初创建模型实例后,url保持不变。
艺术家模型
extend FriendlyId
friendly_id :name, use: [:slugged, :history]
用户控制器
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
答案 0 :(得分:1)
虽然它在docs中声明了在您的控制器中为FriendlyID 5更改网址的代码从未真正解释过。我最终必须添加@artist.slug = nil
才能生效:
def update
@artist.slug = nil
if @artist.update_attributes(artist_params)
flash[:notice] = 'Artist successfully updated'
redirect_to @artist
else
render 'edit'
end
end