使用friendly_id更新属性后无法更改URL路径

时间:2014-06-27 14:58:08

标签: ruby-on-rails friendly-id

我一直在关注如何实施friendly_id的Railscast教程,由于某些原因,我的网址在更新我的属性后没有改变。

说我注册了一个用户:全名' John Doe'它成功地创造了slug / john-doe。但是,如果我将我的名字更新为'测试用户'网址仍然是/ john-doe

我目前的设置是:

users_controller

def show
 @user = User.friendly.find(params[:id])
end

model - user.rb

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

我也已迁移

class AddSlugsToUsers < ActiveRecord::Migration
 def change
  add_column :users, :slug, :string
  add_index :users, :slug, unique: true
 end
end

这样才有用。还安装了

rails generate friendly_id

并完成:

User.find_each(&:save)

in rails c

我做错了什么?

1 个答案:

答案 0 :(得分:3)

<强> friendly_id

这是friendly_id的一个常见问题 - it defaults to setting the slug only if the slug attribute is blank


<强>文档

  

从FriendlyId 5.0开始,slug仅在slug字段时生成   零。如果要重新生成slug,请将slug字段设置为nil:

restaurant.friendly_id # joes-diner
restaurant.name = "The Plaza Diner"
restaurant.save!
restaurant.friendly_id # joes-diner
restaurant.slug = nil
restaurant.save!
restaurant.friendly_id # the-plaza-diner

您还可以覆盖#should_generate_new_friendly_id?方法,可让您准确控制何时设置新的友好ID:

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, :use => :slugged

  def should_generate_new_friendly_id?
    title_changed?
  end
end

如果您想扩展默认行为,但是添加自己的条件,请不要忘记从您的实现中调用super:

class Category < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, :use => :slugged

  def should_generate_new_friendly_id?
    name_changed? || super
  end
end

对你而言,我建议:

#app/models/user.rb
Class User < ActiveRecord::Base
   ...

   def should_generate_new_friendly_id?
      name_changed? || super
   end
end