#221 Subdomains in Rails 3
It is now possible to add subdomains to Rails 3 without the use of additional plugins. Learn how in this episode.
- Download:
- source codeProject Files in Zip (109 KB)
- mp4Full Size H.264 Video (19.6 MB)
- m4vSmaller H.264 Video (13.7 MB)
- webmFull Size VP8 Video (35.2 MB)
- ogvFull Size Theora Video (26.4 MB)
Resources
Note: If you are using Rails 3.1 or later, be certain to check out revised episode 123.
routes.rb
constraints(Subdomain) do
match '/' => 'blogs#show'
end
constraints(Subdomain) do match '/' => 'blogs#show' end
lib/subdomain.rb
class Subdomain
def self.matches?(request)
request.subdomain.present? && request.subdomain != "www"
end
end
class Subdomain def self.matches?(request) request.subdomain.present? && request.subdomain != "www" end end
app/helpers/url_helper.rb
module UrlHelper
def with_subdomain(subdomain)
subdomain = (subdomain || "")
subdomain += "." unless subdomain.empty?
[subdomain, request.domain, request.port_string].join
end
def url_for(options = nil)
if options.kind_of?(Hash) && options.has_key?(:subdomain)
options[:host] = with_subdomain(options.delete(:subdomain))
end
super
end
end
module UrlHelper def with_subdomain(subdomain) subdomain = (subdomain || "") subdomain += "." unless subdomain.empty? [subdomain, request.domain, request.port_string].join end def url_for(options = nil) if options.kind_of?(Hash) && options.has_key?(:subdomain) options[:host] = with_subdomain(options.delete(:subdomain)) end super end end
application_controller.rb
include UrlHelper
include UrlHelper
config/initializers/session_store.rb
# requires Rails 3.0 RC or head
Rails.application.config.session_store :cookie_store, :key => '_blogs_session', :domain => :all
# change top level domain size
request.domain(2)
request.subdomain(2)
Rails.application.config.session_store :cookie_store, :key => '_blogs_session', :domain => "example.co.uk"
# requires Rails 3.0 RC or head Rails.application.config.session_store :cookie_store, :key => '_blogs_session', :domain => :all # change top level domain size request.domain(2) request.subdomain(2) Rails.application.config.session_store :cookie_store, :key => '_blogs_session', :domain => "example.co.uk"
blogs/index.html.erb
<%= link_to blog.name, root_url(:subdomain => blog.subdomain) %>
<%= link_to blog.name, root_url(:subdomain => blog.subdomain) %>
blogs/show.html.erb
<%= link_to "All Blogs", root_url(:subdomain => false) %>
<%= link_to "All Blogs", root_url(:subdomain => false) %>
