问题
I've set up the friendly_id gem, following along to the RailsCasts Screencast on it. Locally this works brilliantly, I installed it, ran through User.find_each(&:save)
which successfully updated the slug field on each of the existing users and all was fine.
I have now pushed this to Heroku, and although it works fine for any new members that are added, Heroku isn't updating the user slug for me for already existing Users.
Running heroku run console
and then User.find_each(&:save)
just does nothing:
irb(main):001:0> User.find_each(&:save)
User Load (20.2ms) SELECT "users".* FROM "users" WHERE ("users"."id" >= 0) ORDER BY "users"."id" ASC LIMIT 1000
(23.6ms) BEGIN
(2.0ms) COMMIT
(13.6ms) BEGIN
(21.1ms) COMMIT
=> nil
The relevant code in models/user.rb
is:
extend FriendlyId
friendly_id :name, use: :slugged
def should_generate_new_friendly_id?
new_record?
end
And I've run all DB migrations on Heroku and they went fine. I checked and the users
table does have a slug
field, but it's empty and I'm not sure where I'm going wrong here. If anyone happens to have come across this before, any advice would be much appreciated. Thank you.
回答1:
And of course, it's always something silly. I'm really not sure how I missed this:
This piece of code:
def should_generate_new_friendly_id?
new_record?
end
Which is there to stop new slugs being made if the name is changed, was also stopping it updating previous posts.
I solved the issue by commenting this out, pushing, running the Heroku console & then User.find_each(&:save)
worked just fine, I then un-commented the code & pushed to Heroku again, and everything is dandy.
Hopefully this may help someone in the future!
回答2:
In my case it was history:
friendly_id :text, use: [:slugged, :history]
Had to be
friendly_id :text, use: :slugged
To make the heroku save work... I then readded the history part
回答3:
I was able to fix this issue by changing my should_generate_new_friendly_id?
method from
def should_generate_new_friendly_id?
title_changed?
end
to
def should_generate_new_friendly_id?
slug.nil? || title_changed?
end
来源:https://stackoverflow.com/questions/10957505/rails-friendly-id-on-heroku-heroku-not-updating-slugs