2014-11-01 64 views
0

继以下两个网友的wikirailscast我试着重写和重定向我的网址,如果我的用户模型的名称已更改。遗憾的是,没有发生。我跑了适当的迁移:FriendlyID历史记录不适用于Rails中的更新模型网址

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

所以我不知道这是否是问题你没有张贴代码为'update'方法,但是你需要设置'为了重新生成“slug”到“nil”。 – 2014-11-01 04:17:31

+0

@ViniciusPinto我已更新我的问题以显示更新操作中的内容(从脚手架生成的默认代码)。你会推荐我做什么? – 2014-11-01 04:39:52

+0

在调用'update_attributes()' – 2014-11-01 04:51:23

回答

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 
+0

'@artist.slug = nil'应该在调用'update_attributes'之前 – 2014-11-01 04:58:05

+0

这看起来是不是正确? – 2014-11-01 04:59:43

+0

看起来不错,但你不能运行代码? – 2014-11-01 05:02:28

相关问题