2023-11-09

Using scope module in routes

Use namespace when you want to group routes under a common module (which will also affect the URL and helper methods). Use scope when you need more flexibility in terms of paths and controller organization, allowing you to keep the controller in the global namespace or in a different module than the URL might imply. The scope is often used when the URL structure doesn’t neatly map to the controller structure, which can sometimes be the case with APIs or user-facing URLs that need to be more SEO-friendly.

resources :posts do
	scope module: :posts do
		resources :publishes, only: :create
	end
end
# app/controllers/posts/publishes_controller.rb
class Posts::PublishesController < ApplicationController
	def create
		
	end
end
Prefix         Verb   URI Pattern          Controller#Action
post_publishes POST   /posts/:post_id/publishes(.:format)     posts/publishes#create

If we were to use namespace, it could look something like this.

namespace :posts do
	post `publishes/create`
end