• Stars
    star
    272
  • Rank 151,235 (Top 3 %)
  • Language
    Ruby
  • Created about 13 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An example Rails 3.2 app with subdomains and authentication using Devise. With a tutorial.

Rails Application for Subdomains with Devise Rails App for Subdomains with Devise

Rails 3.2 example application shows how to use subdomains with Devise for authentication.

  • Devise gives you ready-made authentication and user management.
  • MongoDB is used as a datastore with the Mongoid gem for quick development without schemas or migrations.

Best of all, there’s a detailed tutorial to show how it’s built.

You can build this application in only a few minutes using the Rails Composer tool.

Follow on Twitter Follow on Twitter

Follow the project on Twitter: @rails_apps. Please tweet some praise if you like what you’ve found.

Tutorial

A complete walkthrough tutorial is available on the GitHub wiki:

View the Tutorial

The tutorial documents each step to follow to create the 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 recommended resources for Rails.

What Is Implemented — and What Is Not

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.

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 “[email protected]@” 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.

RailsApps Examples and Tutorials

This is one in a series of Rails example apps and tutorials from the RailsApps Project. See a list of additional Rails examples, tutorials, and starter apps.

Dependencies

Before running this app, you will need:

  • The Ruby language (version 1.9.3 or 2.0.0)
  • The Rails gem (version 3.2.13)
  • A working installation of MongoDB (version 1.6.0 or newer)

See the article Installing Rails for advice about updating Rails and your development environment.

Installing MongoDB

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 Homebrew and then run the following:

brew install mongodb

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, /usr/local/Cellar/mongodb/1.8.0-x86_64). You’ll find the MongoDB configuration file there. After an installation using Homebrew, the default data directory will be /usr/local/var/mongodb.

Getting the Application

You have several options for getting the code.

Fork

If you’d like to add features (or bug fixes) to improve the example application, you can fork the GitHub repo and make pull requests. Your code contributions are welcome!

Clone

If you want to copy and customize the app with changes that are only useful for your own project, you can clone the GitHub repo. You’ll need to search-and-replace the project name throughout the application. You probably should generate the app instead (see below). To clone:

$ git clone git://github.com/RailsApps/rails3-subdomains.git

You’ll need git on your machine. See Rails and Git.

Generate

If you want to use the project as a starter app, use the Rails Composer tool to generate a new version of the example app. You’ll be able to give it your own project name when you generate the app. Generating the application gives you many additional options.

To build the example application, run the command:

$ rails new rails3-subdomains -m https://raw.github.com/RailsApps/rails-composer/master/composer-Rails3_2.rb -T -O

Use the -T -O flags to skip Test::Unit files and Active Record files.

The $ character indicates a shell prompt; don’t include it when you run the command.

This creates a new Rails app named rails3-subdomains on your computer.

You’ll see a prompt:

question  Install an example application?
      1)  I want to build my own application
      2)  membership/subscription/saas
      3)  rails-prelaunch-signup
      4)  rails3-bootstrap-devise-cancan
      5)  rails3-devise-rspec-cucumber
      6)  rails3-mongoid-devise
      7)  rails3-mongoid-omniauth
      8)  rails3-subdomains

Choose rails3-subdomains. The Rails Composer tool may give you other options (other choices may have been added since these notes were written).

The application generator template will ask you for additional preferences:

 question  Web server for development?
       1)  WEBrick (default)
       2)  Thin
       3)  Unicorn
       4)  Puma
 question  Web server for production?
       1)  Same as development
       2)  Thin
       3)  Unicorn
       4)  Puma
 question  Template engine?
       1)  ERB
       2)  Haml
       3)  Slim
   extras  Set a robots.txt file to ban spiders? (y/n)
   extras  Use or create a project-specific rvm gemset? (y/n)
   extras  Create a GitHub repository? (y/n)

Web Servers

Use the default WEBrick server for convenience. If you plan to deploy to Heroku, select “thin” as your production webserver.

Template Engine

The example application uses the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml or Slim. See instructions for Haml and Rails.

Other Choices

Set a robots.txt file to ban spiders if you want to keep your new site out of Google search results.

It is a good idea to use rvm, the Ruby Version Manager, and create a project-specific rvm gemset (not available on Windows). See Installing Rails.

If you choose to create a GitHub repository, the generator will prompt you for a GitHub username and password.

Troubleshooting

If you get an error “OpenSSL certificate verify failed” or “Gem::RemoteFetcher::FetchError: SSL_connect” see the article OpenSSL errors and Rails.

If you get an error like this:

Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
    composer  Running 'after bundler' callbacks.
The template [...] could not be loaded.
Error: You have already activated ..., but your Gemfile requires ....
Using bundle exec may solve this.

It’s due to conflicting gem versions. See the article Rails Error: “You have already activated (…)”.

Other problems? Check the issues.

Edit the README

If you’re storing the app in a GitHub repository, please edit the README files to add a description of the app and your contact info. If you don’t change the README, people will think I am the author of your version of the application.

Getting Started

Install the Required Gems

Check the Gemfile to see which gems are used by this application.

If you used the Rails Composer tool to generate the example app, the application template script has already run the bundle install command.

If not, you should run the bundle install command to install the required gems on your computer:

$ bundle install

You can check which gems are installed on your computer with:

$ gem list

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.

I recommend using rvm, the Ruby Version Manager, to create a project-specific gemset for the application. See the article Installing Rails.

Configure Mongoid

Mongoid provides access to the MongoDB database from Rails.

You can use the default configuration found in the file config/mongoid.yml.

If you want to see what’s in your MongoDB databases, I recommend using the MongoHub app (for Mac OS X).

Configure Email

This example application doesn’t send email messages. However, if you want your application to send email messages (for example, if you plan to install the Devise :confirmable module) you must configure the application for your email account. See the article Send Email with Rails.

Configure Devise

You can modify the configuration file for Devise if you want to use something other than the defaults:

  • config/initializers/devise.rb

Configuration File

The application uses the figaro gem to set environment variables. Credentials for your administrator account and email account are set in the config/application.yml file. The .gitignore file prevents the config/application.yml file from being saved in the git repository so your credentials are kept private. See the article Rails Environment Variables for more information.

Modify the file config/application.yml:

# Add account credentials and API keys here.
# See http://railsapps.github.io/rails-environment-variables.html
# This file should be listed in .gitignore to keep your settings secret!
# Each entry sets a local environment variable and overrides ENV variables in the Unix shell.
# For example, setting:
# GMAIL_USERNAME: Your_Gmail_Username
# makes 'Your_Gmail_Username' available as ENV["GMAIL_USERNAME"]
# Add application configuration variables here, as shown below.
#
GMAIL_USERNAME: Your_Username
GMAIL_PASSWORD: Your_Password
ADMIN_NAME: user1
ADMIN_EMAIL: [email protected]
ADMIN_PASSWORD: changeme

If you are planning to customize the application to send email using a Gmail account, you can add the user name and password needed for the application to send email. See the article Send Email with Rails.

If you wish, set your name, email address, and password for the first user’s account. If you prefer, you can use the default to sign in to the application and edit the account after deployment. It is always a good idea to change the password after the application is deployed.

All configuration values in the config/application.yml file are available anywhere in the application as environment variables. For example, ENV["GMAIL_USERNAME"] will return the string “Your_Username”.

If you prefer, you can delete the config/application.yml file and set each value as an environment variable in the Unix shell.

Set Up a Database Seed File

The db/seeds.rb file initializes the database with default values. To keep some data private, and consolidate configuration settings in a single location, we use the config/application.yml file to set environment variables and then use the environment variables in the db/seeds.rb file.

puts 'DEFAULT USERS'
user = User.create! :name => ENV['ADMIN_NAME'].dup, :email => ENV['ADMIN_EMAIL'].dup, :password => ENV['ADMIN_PASSWORD'].dup, :password_confirmation => ENV['ADMIN_PASSWORD'].dup
puts 'user: ' << user.name

You can change the first user’s name, email, and password in this file but it is better to make the changes in the config/application.yml file to keep the credentials private. If you decide to include your private password in the db/seeds.rb file, be sure to add the filename to your .gitignore file so that your password doesn’t become available in your public GitHub repository.

Note that it’s not necessary to personalize the db/seeds.rb file before you deploy your app. You can deploy the app with an example user and then use the application’s “Edit Account” feature to change name, email address, and password after you log in. Use this feature to log in as the first user and change the user name and password to your own.

You may wish to include additional sample users:

user2 = User.create! :name => 'user2', :email => '[email protected]', :password => 'changeme', :password_confirmation => 'changeme'
puts 'user: ' << user2.name

This will add a second user to the database.

Set the Database

Prepare the database and add the default user to the database by running the commands:

$ rake db:seed

Use rake db:reseed if you want to empty and reseed the database. Or you can use rake db:drop and rake db:setup. The equivalent task for Rails with ActiveRecord is rake db:reset which will be available in Mongoid 4.0.

Set the database for running tests:

$ rake db:test:prepare

If you’re not using rvm, the Ruby Version Manager, you should preface each rake command with bundle exec. You don’t need to use bundle exec if you are using rvm version 1.11.0 or newer.

Change your Application’s Secret Token

If you’ve used the Rails Composer tool to generate the application, the application’s secret token will be unique, just as with any Rails application generated with the rails new command.

However, if you’ve cloned the application directly from GitHub, it is crucial that you change the application’s secret token before deploying your application in production mode. Otherwise, people could change their session information, and potentially access your site without your permission. Your secret token should be at least 30 characters long and completely random.

Get a unique secret token:

rake secret

Edit your config/initializers/secret_token.rb file to add the secret token:

Rails3Subdomains::Application.config.secret_token = '...some really long, random string...'

Test the Application With Subdomains

If you launch the application, it will be running at http://localhost:3000/ or http://0.0.0.0:3000/. 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 http://foo.localhost:3000/. 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 /etc/hosts file (but it won’t accommodate dynamically created subdomains). You can create a proxy auto-config file and set it up as the proxy in your web browser preferences.There’s a far simpler solution that does not require reconfiguring your computer or web browser preferences. The developer Levi Cook registered a domain, lvh.me (short for: local virtual host me), that resolves to the localhost IP address 127.0.0.1 and supports wildcards (accommodating dynamically created subdomains).

To test the application, visit http://lvh.me:3000/. You should see a list of registered users with links to their profile pages.

Try http://user1.lvh.me:3000/. You should see the profile page for the default user “user1.”

Try http://foo.lvh.me:3000/. You should see the “user not found” error message.

Try http://www.lvh.me:3000/. You should be redirected to the application home page at http://lvh.me:3000/.

To sign in as the default user, (unless you’ve changed it) use

You should delete or change the pre-configured logins before you deploy your application.

Deploy to Heroku

For your convenience, here are instructions for deploying your app to Heroku. Heroku provides low cost, easily configured Rails application hosting.

Customizing

Devise provides a variety of features for implementing authentication. See the Devise documentation for options.

This example application and tutorial demonstrates Devise and Mongoid working together on Rails 3. Add any models, controllers, and views that you need.

Testing

The application is set up for RSpec unit tests and Cucumber scenarios and steps. No tests and scenarios are implemented for this version of the example application. Please send the author a message, create an issue, or submit a pull request if you can contribute RSpec or Cucumber tests and scenarios.

After installing the application, run rake -T to check that rake tasks for RSpec and Cucumber are available.

Run rake spec to run RSpec tests.

Run rake cucumber (or more simply, cucumber) to run Cucumber scenarios and steps.

Troubleshooting

Problems? Check the issues.

Problems with “Certificate Verify Failed”

Are you getting an error “OpenSSL certificate verify failed” when you try to generate a new Rails app from an application template? See suggestions to resolve the error Certificate Verify Failed.

Documentation and Support

The tutorial provides additional documentation.

For a Mongoid introduction, Ryan Bates offers a Railscast on Mongoid. You can find documentation for Mongoid at http://mongoid.org/ There is an active Mongoid mailing list and you can submit Mongoid issues at GitHub.

For a Devise introduction, Ryan Bates offers a Railscast on Devise. You can find documentation for Devise at http://github.com/plataformatec/devise. There is an active Devise mailing list and you can submit Devise issues at GitHub.

Issues

Please create an issue on GitHub if you identify any problems or have suggestions for improvements.

Where to Get Help

Your best source for help with problems is Stack Overflow. Your issue may have been encountered and addressed by others.

You can also try Rails Hotline, a free telephone hotline for Rails help staffed by volunteers.

Contributing

If you make improvements to this application, please share with others.

Send the author a message, create an issue, or fork the project and submit a pull request.

If you add functionality to this application, create an alternative implementation, or build an application that is similar, please contact me and I’ll add a note to the README so that others can find your work.

Credits

Thank you to Brian Cardarella for a helpful blog post on Custom Subdomains in Rails 3.

Daniel Kehoe implemented the application and wrote the tutorial.

Is the app useful to you? Follow the project on Twitter: @rails_apps
and tweet some praise. I’d love to know you were helped out by what I’ve put together.

MIT License

MIT License

Copyright © 2012 Daniel Kehoe

Useful Links

Getting Started Articles Tutorials
Learn Rails Twitter Bootstrap and Rails Rails and Bootstrap
Ruby and Rails Analytics for Rails
What is Ruby on Rails? Heroku and Rails Devise with CanCan and Twitter Bootstrap
Rails Tutorial JavaScript and Rails Rails Membership Site with Stripe
Installing Rails Rails Environment Variables Rails Subscription Site with Recurly
Updating Rails Git and Rails Startup Prelaunch Signup Application
Rails Composer Email and Rails Devise with RSpec and Cucumber
Rails Examples Haml and Rails Devise with Mongoid
Rails Starter Apps Rails Application Layout OmniAuth with Mongoid
HTML5 Boilerplate for Rails Subdomains with Devise
Example Gemfiles for Rails
Rails Application Templates

githalytics.com alpha

More Repositories

1

rails-composer

Rails Composer. The Rails generator on steroids for starter apps.
Ruby
3,379
star
2

rails_apps_composer

A gem with recipes to create Rails application templates for Rails starter apps.
Ruby
1,423
star
3

rails-stripe-membership-saas

An example Rails 4.2 app with Stripe and the Payola gem for a membership or subscription site.
Ruby
1,140
star
4

rails3-application-templates

Deprecated (no longer maintained). Use the Rails Composer tool instead.
Ruby
572
star
5

rails_layout

Generates Rails application layout files for various front-end frameworks.
HTML
569
star
6

rails-bootstrap

Rails 5.1 starter app with the Bootstrap 4 front-end framework.
Ruby
523
star
7

rails-devise

Rails 5.0 starter app with Devise for authentication.
Ruby
513
star
8

rails3-bootstrap-devise-cancan

Outdated. See the rails-devise-pundit example app for Rails 4.1.
Ruby
491
star
9

rails-devise-pundit

Rails 5.0 starter app with Devise for authentication and Pundit for authorization.
Ruby
484
star
10

rails-prelaunch-signup

An example Rails 3.2 app for a web startup prelaunch site.
Ruby
446
star
11

rails3-devise-rspec-cucumber

An example Rails 3.2 app with Devise and RSpec and Cucumber.
Ruby
445
star
12

rails3-mongoid-devise

An example Rails 3.2 app with Mongoid for data, Devise for authentication.
Ruby
401
star
13

learn-rails

An example Rails 5.1 app to accompany the "Learn Ruby on Rails" book.
Ruby
392
star
14

rails3-mongoid-omniauth

An example Rails 3.2 app with Mongoid for data, OmniAuth for authentication. With a tutorial.
Ruby
287
star
15

rails-omniauth

Rails 5.0 starter app with OmniAuth for authentication.
Ruby
278
star
16

rails-devise-roles

Rails 5.0 starter app with Devise and simple role-based authorization.
Ruby
187
star
17

rails-recurly-subscription-saas

An example Rails 3.2 app with recurring billing using Recurly for a membership or subscription site.
Ruby
171
star
18

rails-stripe-checkout

Rails 5.0 starter app for selling a product using Stripe Checkout
Ruby
100
star
19

rails_apps_testing

Set up a testing framework for a Rails application.
Ruby
98
star
20

rails-foundation

Rails 4.2 starter app with the Zurb Foundation front-end framework.
Ruby
53
star
21

rails-stripe-coupons

Rails 5.0 starter app for selling a product using Stripe JS
Ruby
49
star
22

rails-signup-download

Rails 5.0 starter app allows a visitor to sign up for an account and download a PDF file.
Ruby
42
star
23

rails-mailinglist-activejob

Rails 5.0 starter app using Active Job for background processing.
Ruby
36
star
24

rails_apps_pages

Add pages to a Rails application, including controllers, views, routing, and tests.
HTML
23
star
25

rails-challenges

Slideshow about the difficulties faced by Rails beginners.
11
star
26

rails-signup-thankyou

Rails 5.2 example application with signup, download, and thank you page.
Ruby
11
star
27

railsapps.github.com

Content for the RailsApps website.
HTML
10
star
28

mailinglist.railscomposer.com

Mailing list signup application for Rails Composer.
Ruby
2
star
29

talk-what-is-ror

Slideshow for a talk, "What is Ruby on Rails."
2
star
30

railsapps-org

Website for the RailsApps open source project.
HTML
1
star