Friendly Id Custom Slug

有些话、适合烂在心里 提交于 2019-12-12 11:22:47

问题


I have a Post model

#post.rb   
extend FriendlyId
friendly_id :slug_candidates, use: [:slugged, :history]

I'm trying to customize the url for each post like so

#post.rb 
def slug_candidates
 "#tutorial-#{user.display_name}-#{title}"
end

Friendly id keeps generating UUID slugs while I'd like it to generate a comprehensive url

Typically I get \tutorial-john-49c9938b-ece5-4175-a4a4-0bb2b0f26a27 Instead of \tutorial-john-some-comprehensive-title

Thank you


回答1:


I edited the response, sorry. It seems friendly_id expects an array of slug candidates. As you can see here

please try this:

#post.rb 
def slug_candidates
  [ "#tutorial-#{user.display_name}-#{title}" ]
end



回答2:


Understood. The slug was generated before I saved the title. It was therefore generated with a nil title. I had to override the should_generate_new_friendly_id method

def should_generate_new_friendly_id?
  slug.blank? || title_changed?
end


来源:https://stackoverflow.com/questions/36456989/friendly-id-custom-slug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!