Search code examples
ruby-on-railsroutesruby-on-rails-5router

add dynamic route from rails database model?


How can I add dynamic route from database, using model activeRecord :

I try : (using Rails 5)

Rails.application.routes.draw do
  router = self
  Var.find_by(name: 'pages').value.split(',').each do |page|
    router.get "/#{page}", to: 'application#page', as: page
  end
end

but I have an error when I try start rails server :

`rescue in mysql2_connection': Unknown database 'dale' (ActiveRecord::NoDatabaseError)


Solution

  • You can move the code that access the db to initialize block.

    Rails.application.routes.draw do
      router = self
      Rails.application.config.after_initialize do
          Var.find_by(name: 'pages').value.split(',').each do |page|
            router.get "/#{page}", to: 'application#page', as: page
          end
      end
    end
    

    There is no guarantee that your initializers will run after all the gem initializers, so any initialization code that depends on a given gem having been initialized should go into a config.after_initialize block.

    Rails has 5 initialization events which can be hooked into (listed in the order that they are run): Further details in Rails documentation initialization events