I have a site that gives each user their own subdomain ie cmcollin41.website.com. Each user can also create their own pages for their subdomain site. Because I allow each user to create their own pages I need to create dynamic routes for those pages. I have looked through all of the other questions on SO and I haven't been able to find an answer that helps me solve this problem.
I currently have most of this working from following this blog post: http://codeconnoisseur.org/ramblings/creating-dynamic-routes-at-runtime-in-rails-4.
My main problem is that I set each user based off of the subdomain and I need to access the request.subdomain somewhere (either in routes.rb or the model or even the lib folder) so that I can iterate thru the subdomain user's pages to create the routes.
here is my code:
class User < ActiveRecord::Base
has_many :pages
def self.load
Walkaboutio::Application.routes.draw do
#This doesn't work. I know you can't access the request in the model.
#I've been trying for a while to try and figure out how and where to set
#the user via the request.subdomain so I can create the route for each of
#the users pages.
@account = User.find_by(subdomain: request.subdomain)
@account.pages.all.each do |pg|
get "/#{pg.name}", to: "pages#pages", defaults: { id: pg.id }
end
end
end
end
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_account
private
def set_account
@account ||= User.find_by(subdomain: request.subdomain)
end
helper_method :set_account
end
class PagesController < ApplicationController
def pages
@page = Page.find(params[:id])
@bio = @account.bio
end
end
routes.rb
class SubdomainConstraint
def self.matches?(request)
request.subdomain.present? && request.subdomain != 'www'
end
end
Rails.application.routes.draw do
constraints SubdomainConstraint do
root to: 'pages#show', as: :portfolio
#This is where I load the routes
User.load
get '/users/:id/setup', to: 'users#setup', as: :setup
resources :analytics
resources :calendars
resources :events
resources :users
end
root to: 'pages#index', as: :marketing
get '/auth/:provider/callback', to: 'sessions#create'
get '/auth/failure', to: 'sessions#auth_fail'
get '/sign_out', to: 'sessions#destroy', as: :sign_out
get 'contact', to: 'events#new', as: 'contact'
post 'contact', to: 'events#create'
end
Thank you for your help in advance.