friendly_id生成带ID的slug

And*_*nic 4 ruby-on-rails friendly-id

我正在尝试使用friendly_id gem生成一个"#{id} - #{title}"格式的slug

看起来friendly_id使用before_save,并且无法访问ID属性.

有没有解决这个问题?

# Permalinks
#-----------------------------------------------------------------------------
extend FriendlyId
friendly_id :id_and_title, :use => :slugged

def id_and_title
  "#{id} #{title}"
end
Run Code Online (Sandbox Code Playgroud)

小智 13

您可以to_param在模型中覆盖以包含标题,而不是使用friendly_id

class YourModel < ActiveRecord::Base
  def to_param
    "#{id} #{title}".parameterize
  end
end
Run Code Online (Sandbox Code Playgroud)

这应该具有您不必使用friendly_id的效果.