MKK
MKK

Reputation: 2753

How should I design nested url?

For now, I'm setting up my nested routing like this But in this case,

In spite of the fact there are only 2 records that belong to walmart shop
The ID will be shown as '3'
How can I make this ID as count up style? Should I prepare another column or something?

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

Upvotes: 0

Views: 56

Answers (1)

nzifnab
nzifnab

Reputation: 16120

Does it really matter if the number in the url is the id of the record? If that matters to you, you can make a number 'slug' similar to your shop slug "walmart", "bestbuy" etc. You'll have to make a new column in the topics table and use a before_create filter to increment that value. Something like this:

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

Make sure 'slug' here is a numeric field so the + and sorting work correctly.

Upvotes: 1

Related Questions