0

My question is related to Custom url in ruby on rails

However, I want the user to be able to choose what their page name will be dynamically. I don't want to hard code the page info in the route.rb file (get 'my_page_here ', :to => 'home#index') because my website allows users to create a unique page for their business and choose the URL. For example: www.mallstores.com/mycoolbusiness would actually go to www.mallstores.com/action/public/stores/12345

Is it possible to dynamically add/modify entries in the route.rb file whenever a user creates a new page from my website?

1 Answer 1

2

I think you don't need to modify the route dynamically. You need to use routes dynamic segments so basically you should add the following line at the bottom of your routes.rb.

get '/:store_name(.:format)', to: 'public/stores', as: 'public_stores'

IMPORTANT NOTE You must place this line at the bottom of you routes.rb so it wouldn't affect the other routes and it will be the last route to be tested.

Basically when a use navigate to http://yourdomain.name/store_name the routes.rb will send the request to the public_controller then to stores actions in the stores action you can grab the store_name from the url and look at it in your database then present it to the requester.

You can also utilize the friendly_id gem to enhance the process and to ensure the uniqueness of the store name.


Another Technique

You can place the following code in your routes.rb file

Store.all.each do |store|
  get "/#{store.name.parameterize}", to: 'public#store', store_id: store.id
end
  • You must make sure that the stores names are unique.
  • You should also place this at the bottom of your page to ensure that there will be no conflict.

but I prefer the first rule as it is more clean and what if you have like million store. then this would slow down the performance of your app.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.