ruby on rails - Unable to change URL path after updating attributes with friendly_id -
i've been following railscast tutorial on how implement friendly_id , reason url's doesn't change after update attributes.
say registered user :fullname 'john doe' creates slug /john-doe successfully. if update name 'test user' url still /john-doe
my current setup this:
users_controller
def show @user = user.friendly.find(params[:id]) end
model - user.rb
extend friendlyid friendly_id :fullname, use: [:slugged, :history]
i've migrated
class addslugstousers < activerecord::migration def change add_column :users, :slug, :string add_index :users, :slug, unique: true end end
so working. installed
rails generate friendly_id
and done:
user.find_each(&:save)
in rails c
what doing wrong?
friendly_id
it's common issue friendly_id - it defaults setting slug
if slug
attribute blank:
documentation
as of friendlyid 5.0, slugs generated when slug field nil. if want slug regenerated,set slug field 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
you can override #should_generate_new_friendly_id? method, lets control when new friendly ids set:
class post < activerecord::base extend friendlyid friendly_id :title, :use => :slugged def should_generate_new_friendly_id? title_changed? end end
if want extend default behavior but, adding own conditions, don't forget invoke super implementation:
class category < activerecord::base extend friendlyid friendly_id :name, :use => :slugged def should_generate_new_friendly_id? name_changed? || super end end
for you, i'd recommend:
#app/models/user.rb class user < activerecord::base ... def should_generate_new_friendly_id? name_changed? || super end end
Comments
Post a Comment