how can I get the subdomain value in rails, is there a built-in way to do this?
e.g.
test123.example.com
I want the test123 part of
Rails 3.0 has this capability built-in, you can access the subdomain from request.subdomain
.
You can also route based on the subdomain:
class SupportSubdomain
def self.matches?(request)
request.subdomain == "support"
end
end
Basecamp::Application.routes do
constraints(SupportSubdomain) do
match "/foo/bar", :to => "foo#bar"
end
end
If you're using 2.3, you'll need to use a plugin such as subdomain-fu.
Use the following method inside your controller
request.subdomains
This Returns an array of subdomains
In case you are working with a string, and assuming it can be a true URI, you can do this to extract the subdomain.
require 'uri'
uri = URI.parse('http://test123.example.com')
uri.host.split('.').first
=> "test123"
https://stackoverflow.com/a/13243810/3407381
You can use the SubdomainFu plugin. This plugin gives you a method current_subdomain which returns the current_subdomain of your app.
You can also have a look at this Railscast
UPDATE
You can also use request.subdomains
this will give you an array of subdomains.
A bit late to the party but here's what I used in older versions of rails.
subdomain = request.subdomains.join('.')
It should be backwards compatible in newer versions
account_location is also a good plugin. After using it, you can find the account based on different subdomains. And you can find out subdomain from url just by writing
request.subdomains(0).first
in your code.