Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

421 lines (405 sloc) 33.583 kB
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Rails Tutorial for Subdomains with Devise &#183; RailsApps</title>
<link href="https://plus.google.com/u/0/b/117374718581973393536/117374718581973393536/posts/" rel="publisher" />
<link rel="stylesheet" href="http://railsapps.github.com/css/bootstrap.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="http://railsapps.github.com/css/screen.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="http://railsapps.github.com/css/gollum.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="http://railsapps.github.com/css/site.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="http://railsapps.github.com/css/syntax.css" type="text/css" charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.6.min.js" type="text/javascript"></script>
<script src="http://railsapps.github.com/javascript/jquery.text_selection-1.0.0.min.js" type="text/javascript"></script>
<script src="http://railsapps.github.com/javascript/jquery.previewable_comment_form.js" type="text/javascript"></script>
<script src="http://railsapps.github.com/javascript/jquery.tabs.js" type="text/javascript"></script>
<script src="http://railsapps.github.com/javascript/gollum.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5109366-14']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a href="http://railsapps.github.com/" class="brand">RailsApps Project</a>
<ul class="pull-right nav">
<li><a href="http://blog.railsapps.org/" class="twitter">Blog</a></li>
<li><a href="http://twitter.com/rails_apps" class="twitter">Twitter</a></li>
<li><a href="https://plus.google.com/117374718581973393536" class="google">Google +</a></li>
<li><a href="https://github.com/RailsApps" class="github">GitHub Repository</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="content wikistyle gollum textile">
<h1>Rails Tutorial for Subdomains with Devise</h1>
<h4>by Daniel Kehoe</h4>
<p><em>Last updated 27 February 2012</em></p>
<p>Ruby on Rails tutorial showing how to create a Rails 3.2 application with subdomains and authentication using Devise.</p>
<h4>What Is Implemented</h4>
<p>The example app implements a common use of subdomains, often called “Basecamp-style subdomains in Rails.” Visitors to the main site create a user account which is hosted at a subdomain that matches their user name. Each user has only one subdomain and when they log in, all their activity is confined to their subdomain.</p>
<h4>What Is Not Implemented</h4>
<p>Another common use of subdomains can be called “blog-style subdomains.” This approach is familiar to users of sites such as wordpress.com where each user can create multiple blogs and each is hosted on its own subdomain. For example, a user with the email address “user@example.com@” can own more than one blog, for example, “puppyphotos.wordpress.com” and “kittenphotos.wordpress.com”. The “blog-style subdomains” approach is not implemented in this example application.</p>
<h4>Based on the Rails3-Mongoid-Devise Example App</h4>
<p>This app extends the <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> example app. You can see a <a href="http://railsapps.github.com/tutorial-rails-mongoid-devise.html">tutorial for the Rails 3 + Mongoid + Devise</a>. <a href="http://mongoid.org/">Mongoid</a> gives access to a MongoDB datastore for quick development without schemas or migrations. <a href="http://github.com/plataformatec/devise">Devise</a> gives you ready-made authentication.</p>
<h4>Similar Examples and Tutorials</h4>
<p>See a list of additional <a href="http://railsapps.github.com/rails-examples-tutorials.html">Rails examples, tutorials, and starter apps</a>.</p>
<h2>
<a href="http://www.twitter.com/rails_apps"><img src="http://twitter-badges.s3.amazonaws.com/t_logo-a.png" title="Follow on Twitter" alt="Follow on Twitter"></a> Follow on Twitter</h2>
<p>Follow the project on Twitter: <a href="http://twitter.com/rails_apps">@rails_apps</a>. Tweet some praise if you like what you’ve found.</p>
<h2>
<img src="http://railsapps.github.com/images/rails-36x36.jpg" title="Tutorial" alt="Tutorial"> Tutorial</h2>
<p>This tutorial documents each step that you must follow to create this application. Every step is documented concisely, so a complete beginner can create this application without any additional knowledge. However, no explanation is offered for any of the steps, so if you are a beginner, you’re advised to look for an introduction to Rails elsewhere. See a list of <a href="http://railsapps.github.com/rails.html">top resources for learning Rails</a>.</p>
<h2>Before You Start</h2>
<p>If you follow this tutorial closely, you’ll have a working application that closely matches the example app in this GitHub repository. The example app is your reference implementation. If you find problems with the app you build from this tutorial, download the example app (in Git speak, clone it) and use a file compare tool to identify differences that may be causing errors. On a Mac, <a href="http://stackoverflow.com/questions/187064/graphical-diff-for-mac-os-x">good file compare tools</a> are <a href="http://en.wikipedia.org/wiki/Apple_Developer_Tools#FileMerge">FileMerge</a>, <a href="http://sourcegear.com/diffmerge/">DiffMerge</a>, <a href="http://www.kaleidoscopeapp.com/">Kaleidoscope</a>, or Ian Baird’s <a href="http://www.changesapp.com/">Changes</a>.</p>
<p>If you clone and install the example app and find problems or wish to suggest improvements, please create a <a href="http://github.com/RailsApps/rails3-subdomains/issues">GitHub issue</a>.</p>
<p>To improve this tutorial, please edit this wiki page.</p>
<h2>Creating the Application</h2>
<h4>Option One</h4>
<blockquote>
<p><ins>Cut and paste the code.</ins></p>
</blockquote>
<p>To create the application, you can cut and paste the code from the tutorial into your own files. It’s a bit tedious and error-prone but you’ll have a good opportunity to examine the code closely.</p>
<h4>Option Two</h4>
<blockquote>
<p><ins>Use the ready-made application template to generate the code.</ins></p>
</blockquote>
<p>You can use an application template to generate a new Rails app with code that closely matches the tutorial. You’ll find an application template for this tutorial in the <a href="https://github.com/RailsApps/rails3-application-templates">Rails Application Templates</a> repository.</p>
<p>Use the command:</p>
<p><code>$ rails new myapp -m https://github.com/RailsApps/rails3-application-templates/raw/master/rails3-subdomains-template.rb -T -O</code></p>
<p>Use the <code>-T -O</code> flags to skip Test::Unit files and Active Record files.</p>
<p>This creates a new Rails app (with the name <code>myapp</code>) on your computer. It includes everything in the example app. You can read through the tutorial with the code already on your computer.</p>
<h4>Option Three</h4>
<blockquote>
<p><ins>Use the <a href="https://github.com/RailsApps/rails_apps_composer">rails_apps_composer</a> gem to create a reusuable application template.</ins></p>
</blockquote>
<p>This is optimal if you are creating a “starter app” based on this example app but wish to customize the code for your own preferences.</p>
<p>Each step in this tutorial has a corresponding application template recipe from the <a href="https://github.com/RailsApps/rails_apps_composer">Rails Apps Composer</a> recipes repository. You can create your own application template using the template recipes. To do so, download the <a href="https://github.com/RailsApps/rails_apps_composer">Rails Apps Composer</a> project, customize recipes as needed, and follow the instructions to create a reusable application template file.</p>
<h2>Assumptions</h2>
<p>Before beginning this tutorial, you need to install</p>
<ul>
<li>The Ruby language (version 1.9.3)</li>
<li>Rails 3.1</li>
<li>A working installation of <a href="http://www.mongodb.org/">MongoDB</a>
</li>
</ul><p>Check that appropriate versions of Ruby and Rails are installed in your development environment:<br><code>$ ruby -v</code><br><code>$ rails -v</code></p>
<p>See <a href="http://railsapps.github.com/installing-rails-3-1.html">Installing Rails 3.1</a> and <a href="http://railsapps.github.com/managing-rails-versions-gems.html">Managing Rails Versions and Gems</a> for detailed instructions and advice.</p>
<h4>Installing MongoDB</h4>
<p>If you don’t have MongoDB installed on your computer, you’ll need to install it and set it up to be always running on your computer (run at launch). On Mac OS X, the easiest way to install MongoDB is to install <a href="http://mxcl.github.com/homebrew/">Homebrew</a> and then run the following:</p>
<pre>
brew install mongodb
</pre>
<p>Homebrew will provide post-installation instructions to get MongoDB running. The last line of the installation output shows you the MongoDB install location (for example, <strong>/usr/local/Cellar/mongodb/1.8.0-x86_64</strong>). You’ll find the MongoDB configuration file there. After an installation using Homebrew, the default data directory will be <strong>/usr/local/var/mongodb</strong>.</p>
<h2>Create the Rails Application</h2>
<p>You’ll start by generating the <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> example app using an application template.</p>
<p>Use the command:</p>
<p><code>$ rails new rails3-subdomains -m https://github.com/RailsApps/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb -T -O</code></p>
<p>Use the <code>-T -O</code> flags to skip Test::Unit files and Active Record files.</p>
<p>This creates a new Rails app (named <code>rails3-subdomains</code>) on your computer. For this tutorial, the name is “rails3-subdomains.” You can use a different name if you wish.</p>
<p>The application generator template will ask you for your preferences. For this tutorial, choose the following preferences:</p>
<p>Would you like to use jQuery? <strong>Yes.</strong><br>
Would you like to use jQuery UI? <strong>No.</strong><br>
Would you like to use Haml instead of <span class="caps">ERB</span>? <strong>Yes.</strong><br>
Would you like to use RSpec instead of TestUnit? <strong>Yes.</strong><br>
Would you like to use factory_girl for test fixtures with RSpec? <strong>Yes.</strong><br>
Would you like to use Cucumber for your <span class="caps">BDD</span>? <strong>Yes.</strong><br>
Would you like to use Guard to automate your workflow? <strong>No.</strong><br>
Would you like to enable the LiveReload guard? <strong>No.</strong><br>
Would you like to use Mongoid to connect to a MongoDB database? <strong>Yes.</strong><br>
Would you like to use Devise for authentication? <strong>Yes.</strong><br>
Which front-end framework would you like for HTML5 and CSS3? <strong>Zurb Foundation</strong><br>
Would you like to set a robots.txt file to ban spiders? <strong>Yes.</strong><br>
Would you like to use ‘rails-footnotes’ during development? <strong>No.</strong></p>
<p>After you create the application, switch to its folder to continue work directly in the application:</p>
<p><code>$ cd rails3-subdomains</code></p>
<h4>Please Remember: Edit the <span class="caps">README</span>
</h4>
<p>If you’re open sourcing the app on GitHub, please edit the <span class="caps">README</span> file to add a description of the app and your contact info. Changing the <span class="caps">README</span> is important if you’re using a clone of the example app. I’ve been mistaken (and contacted) as the author of apps that are copied from my example.</p>
<h2>Set Up Source Control (Git)</h2>
<p>If you’re creating an app for deployment into production, you’ll want to set up a source control repository at this point. If you are building a throw-away app for your own education, you may skip this step.</p>
<p>See instructions for <a href="http://railsapps.github.com/rails-git.html">Using Git with Rails</a>.</p>
<h2>Set Up Gems</h2>
<h4>About Required Gems</h4>
<p>The application uses the following gems:</p>
<ul>
<li><a href="http://rubygems.org/gems/rails">rails</a></li>
<li><a href="http://rubygems.org/gems/rspec-rails">rspec-rails</a></li>
<li><a href="http://rubygems.org/gems/database_cleaner">database_cleaner</a></li>
<li><a href="http://rubygems.org/gems/factory_girl_rails">factory_girl_rails</a></li>
<li><a href="http://rubygems.org/gems/cucumber-rails">cucumber-rails</a></li>
<li><a href="http://rubygems.org/gems/capybara">capybara</a></li>
<li><a href="http://rubygems.org/gems/mongoid">mongoid</a></li>
<li><a href="http://rubygems.org/gems/bson_ext">bson_ext</a></li>
<li><a href="http://rubygems.org/gems/devise">devise</a></li>
</ul><h4>jQuery</h4>
<p>Rails 3.1 uses jQuery by default so no additional effort is required.</p>
<h4>Haml</h4>
<p>In this example, we’ll use Haml instead of the default “<span class="caps">ERB</span>” Rails template engine. The <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> example app sets up Haml. You can see details about <a href="http://railsapps.github.com/rails-haml.html">adding Haml to Rails</a>.</p>
<h4>RSpec</h4>
<p>The <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> example app uses RSpec for unit testing. Run <code>rake -T</code> to check that rake tasks for RSpec are available. You should be able to run <code>rake spec</code> to run all specs provided with the example app.</p>
<h4>Cucumber</h4>
<p>The <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> example app sets up Cucumber for specifications and acceptance testing. You should be able to run <code>rake cucumber</code> (or more simply, <code>cucumber</code>) to run the Cucumber scenarios and steps provided with the example app.</p>
<h4>Mongoid</h4>
<p>The <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> example app uses Mongoid for access to a a MongoDB datastore. The datastore is initialized with a default user in the the file <strong>db/seeds.rb</strong>.</p>
<p>If you need to, you can run <code>$ rake db:reset</code> to drop and then recreate the database using your seeds.rb file.</p>
<h4>Set up Your Gemfile</h4>
<p>The <a href="https://github.com/RailsApps/rails3-mongoid-devise">Rails 3 + Mongoid + Devise</a> application template sets up your gemfile.</p>
<p>See an example <a href="http://railsapps.github.com/rails-3-1-1-example-gemfile.html">Rails 3.1.1 Gemfile</a>.</p>
<p>See <a href="http://railsapps.github.com/managing-rails-versions-gems.html">Managing Rails Versions and Gems</a> for advice and details. It’s a good idea to create a new gemset using rvm, the <a href="http://rvm.beginrescueend.com/">Ruby Version Manager</a>.</p>
<h4>Install the Required Gems</h4>
<p>Install the required gems on your computer:</p>
<p><code>$ bundle install</code></p>
<p>You can check which gems are installed on your computer with:</p>
<p><code>$ gem list --local</code></p>
<p>Keep in mind that you have installed these gems locally. When you deploy the app to another server, the same gems (and versions) must be available.</p>
<h2>Test the App</h2>
<h4>Seed the Database</h4>
<p>Add the default user to the MongoDB database by running the command:</p>
<p><code>$ rake db:seed</code></p>
<h4>Test the App</h4>
<p>You can check that your app runs properly by entering the command</p>
<p><code>$ rails server</code></p>
<p>To see your application in action, open a browser window and navigate to <a href="http://localhost:3000">http://localhost:3000/</a>. You should see the default user listed on the home page. When you click on the user’s name, you should be required to log in before seeing the user’s detail page.</p>
<p>To sign in as the default user, (unless you’ve changed it) use</p>
<ul>
<li>email: user@example.com</li>
<li>password: please</li>
</ul><p>You should delete or change the pre-configured logins before you deploy your application.</p>
<p>Stop the server with Control-C.</p>
<h2>One Subdomain Per User</h2>
<h4>Use Case</h4>
<p>Each user will have access to their own profile page with a unique <span class="caps">URL</span> that includes a custom subdomain. When a user creates a new account, they will be given an opportunity to specify a user ID that will be used as the subdomain. For example, when I sign up for an account, I might specify my User ID as “kehoe” and my profile page will be available at <code>kehoe.example.com</code>.</p>
<h4>User Name as a Subdomain</h4>
<p>The rails3-mongoid-devise example app has a field in the User model named “name.” We’ll use this for the user-specific subdomain.</p>
<p>If you wish, you could rename the “name” field as “subdomain” or “account” or use another label that better matches the requirements of your application. You could also add fields to the User model such as “firstname” and “lastname.” If you do so, you’ll need to change the forms in the <strong>app/views/devise/registrations</strong> directory as well as <strong>app/models/user.rb</strong>. For simplicity, we’ll just use the “name” field to set the subdomain.</p>
<p>In its current form, the User model allows any string to be stored as the user name. To use it as a subdomain, we’ll need to make sure it only contains alphanumeric characters (with an optional underscore). We’ll also limit the name to a maximum of 32 characters. Finally, we don’t want users to choose names such as “www” that will result in URLs such as “http://www.myapp.com”.</p>
<p>Modify <strong>app/models/user.rb</strong> to add the following validations:</p>
<pre>
validates_format_of :name, with: /^[a-z0-9_]+$/, message: "must be lowercase alphanumerics only"
validates_length_of :name, maximum: 32, message: "exceeds maximum of 32 characters"
validates_exclusion_of :name, in: ['www', 'mail', 'ftp'], message: "is not available"
</pre>
<p>We’ll modify the <strong>db/seeds.rb</strong> file to supply an appropriate user name when we initialize the datastore:</p>
<pre>
# user = User.create! :name =&gt; 'First User', :email =&gt; 'user@example.com', :password =&gt; 'please', :password_confirmation =&gt; 'please'
user = User.create! :name =&gt; 'myname', :email =&gt; 'user@example.com', :password =&gt; 'please', :password_confirmation =&gt; 'please'
</pre>
<h2>User’s Profile Page</h2>
<h4>Use Case</h4>
<p>We’ll display a profile page for a user when anyone enters a <span class="caps">URL</span> with a subdomain that matches an existing user. For example, visiting <code>kehoe.example.com</code> will display kehoe’s profile page.</p>
<h4>Controller and Views for the Profile Page</h4>
<p>Create a controller for profiles:</p>
<pre>
$ rails generate controller Profiles show
</pre>
<p>Before we display a profile, we’ll try to find the user with a name that matches the subdomain attribute of the request object. If the user is not found, we’ll raise an exception and display an error message.</p>
<p><strong>app/controllers/profiles_controller.rb</strong></p>
<pre>
class ProfilesController &lt; ApplicationController
def show
@user = User.first(conditions: { name: request.subdomain }) || not_found
end
def not_found
raise ActionController::RoutingError.new('User Not Found')
end
end
</pre>
<p>Next, modify the view to display a user’s profile. Add the following code:</p>
<p><strong>app/views/profile/show.html.haml</strong></p>
<pre>
%h1 Profile
%h4= @user.name
%h4= @user.email
</pre>
<h2>Remove Access Control for the Users Page</h2>
<p>As implemented in rails3-mongoid-devise example app, no visitor can view the user detail page (user/show) if they are not logged in. That serves to demonstrate use of authentication implemented as a filter in the Users controller. We’ll remove this feature by commenting out <code>before_filter :authenticate_user!</code> to simplify our demonstration of subdomains.</p>
<p><strong>app/controllers/users_controller.rb</strong></p>
<pre>
class UsersController &lt; ApplicationController
# before_filter :authenticate_user!
def show
@user = User.find(params[:id])
end
end
</pre>
<p>Skip this step if you want to retain access control to prevent display of the user detail page.</p>
<p>You also might want to limit access so only an administrator can see the user detail page. For implementation suggestions, seethe Devise wiki for <a href="https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role">How to add an admin role</a>.</p>
<h2>Implement Routing for Subdomains</h2>
<p>Rails 3.0 introduced support for routing constrained by subdomains.</p>
<p>A subdomain can be specified explicitly, like this:</p>
<pre>
match '/' =&gt; 'home#index', :constraints =&gt; { :subdomain =&gt; 'www' }
</pre>
<p>Or a set of subdomains can be matched using a regular expression:</p>
<pre>
match '/' =&gt; 'profiles#show', :constraints =&gt; { :subdomain =&gt; /.+/ }
</pre>
<p>Finally, for greatest flexibility, router constraints can also take objects, allowing custom code.</p>
<p>Create a class like this:</p>
<p><strong>lib/subdomain.rb</strong></p>
<pre>
class Subdomain
def self.matches?(request)
case request.subdomain
when 'www', '', nil
false
else
true
end
end
end
</pre>
<p>This class allows use of a route when a subdomain is present in the request object. If the subdomain is “www,” the class will respond as if a subdomain is not present.</p>
<p>Make sure the class is autoloaded when the application starts. You can <code>require 'subdomain'</code> at the top of the <strong>config/routes.rb</strong> file. Or you can modify the file <strong>config/application.rb</strong> (recommended):</p>
<pre>
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(#{config.root}/lib)
</pre>
<p>Use this class when you create routes in the file <strong>config/routes.rb</strong>:</p>
<pre>
devise_for :users
resources :users, :only =&gt; :show
constraints(Subdomain) do
match '/' =&gt; 'profiles#show'
end
root :to =&gt; "home#index"
</pre>
<p>A match from a “/” <span class="caps">URL</span> (such as http://myname.myapp.com) will route to the <code>show</code> action of the <code>Profiles</code> controller only when a subdomain is present. If a subdomain is not present (or is “www”), a route with less priority will be applied (in this case, a route to the <code>index</code> action of the <code>Home</code> controller).</p>
<p>Be sure to comment out (or remove) the route that was added by the Rails generator when we created the controller:</p>
<pre>
#get "profiles/show"
</pre>
<h2>
<span class="caps">URL</span> Helpers With Subdomains</h2>
<p>Applications that do not use subdomains use routing helpers to generate links that either include the site’s hostname (for example, <code>users_url</code> generates <code>http://mysite.com/users</code>) or links that only contain a relative path (for example, <code>users_path</code> generates <code>/users</code>). To provide navigation between sites hosted on the subdomains and the main site, you must use <span class="caps">URL</span> helpers (“users_url”) not path helpers (“users_path”) because path helpers do not include a hostname.</p>
<p>Rails 3.1 provides a way to include a subdomain as part of the hostname when generating links.</p>
<p>You can specify a hostname when creating a link, with the syntax:</p>
<p><code>root_url(:subdomain =&gt; @subdomain)</code></p>
<p>If you need a link to the main site (a <span class="caps">URL</span> without a subdomain), you can force the <span class="caps">URL</span> helper to drop the subdomain:</p>
<p><code>root_url(:host =&gt; request.domain)</code></p>
<p>It should be possible to use <code>root_url(:subdomain =&gt; false)</code> but it seems there is an unresolved issue in Rails 3.1 (see <a href="https://github.com/rails/rails/issues/2025">https://github.com/rails/rails/issues/2025</a>).</p>
<h4>Home Page</h4>
<p>The rails3-mongoid-devise example app provides a home page that lists all registered users. We’ll modify the home page to add a link to each user’s profile page, using a <span class="caps">URL</span> with a custom subdomain.</p>
<p><strong>app/views/home/index.html.haml</strong></p>
<pre>
%h3 Home
- @users.each do |user|
%br/
#{user.name} profile: #{link_to root_url(:subdomain =&gt; user.name), root_url(:subdomain =&gt; user.name)}
</pre>
<h4>Modify the Users Page</h4>
<p>We’ll add a link to the user’s profile page on the page that displays a list of all registered users.</p>
<p><strong>app/views/users/show.html.haml</strong></p>
<pre>
%p
User: #{@user.name}
%p
Email: #{@user.email if @user.email}
%p
Profile: #{link_to root_url(:subdomain =&gt; @user.name), root_url(:subdomain =&gt; @user.name)}
</pre>
<h4>Navigation Links</h4>
<p>We want a visitor to sign up on the main site but only log in on their subdomain-hosted site.</p>
<p>We’ll change the navigation links to show “Sign up” on the main site and “Login” on the subdomain sites.</p>
<p><strong>app/views/shared/_navigation.html.haml</strong></p>
<pre>
%li
= link_to 'Main', root_url(:host =&gt; request.domain)
- if request.subdomain.present? &amp;&amp; request.subdomain != "www"
- if user_signed_in?
%li
= link_to('Edit account', edit_user_registration_url)
%li
= link_to('Logout', destroy_user_session_url, :method=&gt;'delete')
- else
%li
= link_to('Login', new_user_session_url)
- else
%li
= link_to('Sign up', new_user_registration_url(:host =&gt; request.domain))
- if user_signed_in?
%li
= link_to('Logout', destroy_user_session_url, :method=&gt;'delete')
</pre>
<h2>Test the Application With Subdomains</h2>
<p>If you launch the application, it will be running at <a href="http://localhost:3000/">http://localhost:3000/</a> or <a href="http://0.0.0.0:3000/">http://0.0.0.0:3000/</a>. However, unless you’ve made some configuration changes to your computer, you won’t be able to resolve an address that uses a subdomain, such as <a href="http://foo.localhost:3000/">http://foo.localhost:3000/</a>.</p>
<h4>Some Options</h4>
<p>There are several complex solutions to this problem. You could set up your own domain name server on your localhost and create an A entry to catch all subdomains. You could modify your <strong>/etc/hosts</strong> file (but it won’t accommodate dynamically created subdomains). You can create a <a href="http://en.wikipedia.org/wiki/Proxy_auto-config" title="PAC">proxy auto-config</a> file and set it up as the proxy in your web browser preferences.</p>
<h4>Use lvh.me</h4>
<p>There’s a far simpler solution that does not require reconfiguring your computer or web browser preferences. The developer Levi Cook registered a domain, <a href="http://lvh.me:3000/">lvh.me</a> (short for: local virtual host me), that resolves to the localhost IP address 127.0.0.1 and supports wildcards (accommodating dynamically created subdomains).</p>
<h4>Seed the Datastore</h4>
<p>You’ve changed the name of the default user in the the <strong>db/seeds.rb</strong> file.</p>
<p>Re-initialize the MongoDB datastore by running the command:</p>
<p><code>$ rake db:seed</code></p>
<h4>Test the App</h4>
<p>Start the app by entering the command</p>
<p><code>$ rails server</code></p>
<p>To test the application, visit <a href="http://lvh.me:3000/">http://lvh.me:3000/</a>. You should see a list of registered users with links to their profile pages.</p>
<p>Try <a href="http://myname.lvh.me:3000/">http://myname.lvh.me:3000/</a>. You should see the profile page for the default user “myname.”</p>
<p>Try <a href="http://foo.lvh.me:3000/">http://foo.lvh.me:3000/</a>. You should see the “user not found” error message.</p>
<p>Try <a href="http://www.lvh.me:3000/">http://www.lvh.me:3000/</a>. You should be redirected to the application home page at <a href="http://lvh.me:3000/">http://lvh.me:3000/</a>.</p>
<h2>Optional: Allow Sessions To Be Shared Across Subdomains</h2>
<p>The application allows a user to log in to either the main site (<a href="http://lvh.me:3000/">http://lvh.me:3000/</a>) or a user site (<a href="http://myname.lvh.me:3000/">http://myname.lvh.me:3000/</a>). Logging in creates a user session. In its current form, the application maintains separate and independent user sessions for the main site and each subdomain. That’s because session data for each visitor is managed by browser-based cookies and cookies are not shared across domains (and, by default, not shared across subdomains). Not only is the user login not maintained between the main site and subdomains, but flash messages (used to communicate between actions) are lost because they are stored in sessions.</p>
<p>For the example application, we want a visitor to sign up on the main site but only log in on their subdomain-hosted site. As implemented, we don’t want sessions to be shared across subdomains.</p>
<p>However, your requirements may differ. If you wish to maintain sessions between the main site and subdomain-hosted sites, modify the configuration file to add the parameter <code>:domain =&gt; :all</code>:</p>
<p><strong>config/initializers/session_store.rb</strong></p>
<pre>
Rails3Subdomains::Application.config.session_store :cookie_store, :key =&gt; '_rails3-subdomains_session', :domain =&gt; :all
</pre>
<h2>Deploy to Heroku</h2>
<p>For your convenience, here are <a href="http://railsapps.github.com/rails-heroku-tutorial.html">instructions for deploying your app to Heroku</a>. Heroku provides low cost, easily configured Rails application hosting.</p>
<h2>Conclusion</h2>
<p>This concludes the tutorial for creating a Rails 3 web application that uses subdomains and provides user management and authentication using Devise.</p>
<h4>Credits</h4>
<p>Thank you to <a href="http://bcardarella.com/">Brian Cardarella</a> for a helpful blog post on <a href="http://bcardarella.com/post/716951242/custom-subdomains-in-rails-3">Custom Subdomains in Rails 3</a>.</p>
<p>Daniel Kehoe (<a href="http://danielkehoe.com/">http://danielkehoe.com/</a>) implemented the application and wrote the tutorial.</p>
<p>Was this useful to you? Follow me on Twitter:<br><a href="http://twitter.com/rails_apps">rails_apps</a><br>
and tweet some praise. I’d love to know you were helped out by the tutorial.</p>
<p>Any issues? Please create an <a href="http://github.com/RailsApps/rails3-subdomains/issues">issue</a> on GitHub.</p>
</div><!-- class="content" -->
<div class="comments">
<div class="content wikistyle gollum">
<h2>Comments and Issues</h2>
</div>
<p>Is this helpful? Please add a comment below. Your encouragement fuels the project.</p>
<p>Did you find an error? Or couldn't get something to work? For the example apps and tutorials, please create a GitHub issue in the repository for the example app. Creating a GitHub issue is the best way to make sure a problem is investigated and fixed.</p>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'railsapps'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div><!-- class="comments" -->
<div class="footer row">
<div class="span4">
<h3>Credits</h3>
<p><a href="http://danielkehoe.com/">Daniel Kehoe</a> initiated the <a href="http://railsapps.github.com/">RailsApps Project</a>. Thanks to all the users and contributors.</p>
</div>
<div class="span4">
<h3>Wiki</h3>
<p>Corrections? Additions? You can edit this page <a href="https://github.com/RailsApps/railsapps.github.com/wiki/_pages">on the wiki</a>.</p>
</div>
<div class="span4">
<h3>Last edit</h3>
<p>by <b>Daniel Kehoe</b>, 2012-07-20 23:08:42</p>
</div>
</div>
</div>
</body>
</html>
Jump to Line
Something went wrong with that request. Please try again.