All threads / How do I create my homepage subdomain ('www')

Ask A Question


You’re not receiving notifications from this thread.

How do I create my homepage subdomain ('www')

Damian Nelwep asked in Rails


I followed the tutorial for subdomain from scratch and got " redirect_to root_url(subdomain: "www") if @account.nil? " but I don't know how to get to manage it as a homepage like home#index.

I wondered if I wouldn't have to change something about " before_action :set_account " in application_controller.rb

thank you in advance

Hey Damian!

It's usually easiest to set that up in your routes file. You can setup a subdomain constraint so that when the subdomain is www or nil, you can render the homepage. Otherwise when there's a subdomain, you can send it to the account controller.

You can put this in app/lib/account_subdomain.rb

class AccountSubdomain
    def self.matches? request
          # www and no subdomain are excluded and don't count as account subdomains
            # You can add any more subdomains to this array to have them ignored.
          !["www", nil].include? request.subdomain

Then your config/routes.rb file can use this to set the constraints:

Rails.application.routes.draw do
    # Account routes
    constraints(AccountSubdomain) do
            root to: "account#index"

        root to: "home#index"

Thank you but I get an error

uninitialized constant AccountSubdomain

Is it normal that I had to create the directory lib/ in the app/ folder ?

I also get
Routing Error
No route matches [GET] "/"

Sorry in fact I just had to restart the server and now it works perfectly thank you so much...

I only have a last issue which is that when I'm in a subdomain and I get to 'home', the subdomain still appear in the url whereas I want 'www' or nil.. :s

I get '' instead of '' or ''

You can pass subdomain: nil into your url helpers to change the subdomain. Something like link_to home_url(subdomain: nil)

Thank you again this is perfectly what I needed. You're the best teacher I could ever dream of but I hope I don't bother you so much with my issues... By the way I think I would be interested in your hosting service but I'll ask you about it later, now is not the time. Hope you're having a good day :)

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 41,443+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.