Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Damian Nelwep asked in Rails

Hi,

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

Reply

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
    end   
end

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"
    end

        root to: "home#index"
end
Reply

Thank you but I get an error

"
NameError
uninitialized constant AccountSubdomain
"

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

Reply

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

Reply

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

Reply

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

Reply

I get 'example.domain.com/home' instead of 'domain.com/home' or 'www.domain.com/home'

Reply

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

Reply

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 :)

Reply
Join the discussion
Create an account Log in

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

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

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