0

现在,我正在像这样设置我的嵌套路由但是在这种情况下,

  • example.com/shop/walmart/topic/1 <= 如果我第一次创建主题
  • example.com/shop/bestbuy/topic/2 <= 如果我第二次创建主题
  • example.com/shop/walmart/topic/3 <= 如果我第三次创建主题

尽管事实上只有 2 条属于walmart shop
的记录 ID 将显示为'3'
我怎样才能使这个 ID 成为计数样式?我应该准备另一个专栏还是什么?

resources :communities, :path => "shop", do
resources :community_topics, :path => "topic", :as => :'topic'
end
4

1 回答 1

1

如果 url 中的数字是记录的数字,这真的很id重要吗?如果这对您很重要,您可以创建一个类似于您的商店 slug“walmart”、“bestbuy”等的数字“slug”。您必须在主题表中创建一个新列并使用before_create过滤器来增加该值。像这样的东西:

class Topic
  before_validation :increment_slug, :on :create
  validates_uniqueness_of :slug, scope: :shop_id

  private
  def increment_slug
    self.slug = Topic.where("shop_id = ?", shop_id).order("slug DESC").limit(1).slug + 1
  end
end

确保此处的“slug”是一个数字字段,以便+正确排序。

于 2012-12-24T18:13:49.227 回答