Learn Rails
A Rails 5.1 example application to accompany the book Learn Ruby on Rails.
The book introduces basic concepts of Rails development by showing the reader how to build an application that can be used for a typical small business website.
You can build this application in only a few minutes using the Rails Composer tool.
The Book Set: âLearn Ruby on Railsâ
This example application is fully documented in the book set Learn Ruby on Rails. May I suggest, you should get the books.
With the books, a complete beginner can create this application without any additional knowledge. The books explain all the code, introducing basic concepts of Rails application development and professional practices.
Book Two, Latest Version: 4.1.0
There are two books. Book One does not contain code from the application and does not change often.
Book Two contains a tutorial application and changes frequently. The most recent version of the book was written for Rails 5.1 and released July 3, 2017. Please make sure you have the newest version of the book (or the code examples may not work). The book version is shown on the title page. Get the book if you need the new version.
Application Version: 4.1.0
This example application (here on GitHub) matches the code in Book Two.
For recent changes, see:
- CHANGELOG for a summary
- commit log for code changes
A Practical Application
The example application is more than a learning exercise. The tutorial shows how to build a basic website, using practices recommended by experienced Rails developers. Youâll build a real-world Rails application that can be used by a typical small business. With knowledge of Rails, the website can be adapted and customized to your needs. Features include:
- Home page
- Navigation bar
- âAboutâ page
- Contact page with âcontact requestâ form
- Mailing list sign-up form
Additional Pages
The application uses the high_voltage gem for the âAboutâ page. Additional pages can easily be added. The high_voltage gem makes it easy to add pages with static content (text that doesnât change) incorporating elements of a site-wide application layout such as header, navigation links, and footer.
For example, using the high_voltage gem, you could add pages for:
- FAQ
- News
- Legal disclaimers
Mailing List Opt-In
The application home page contains a form that encourages a visitor to enter an email address to sign up for a mailing list. It can be used to collect email addresses for a newsletter or announcement mailings. The tutorial shows how to set up a MailChimp account and use the MailChimp API to add email addresses to a MailChimp list.
Contact Form
The Contact page includes a âcontact requestâ form. The contact form can be adapted for other purposes, such as an appointment request, or customized as a survey form.
When the visitor submits the form, an email message goes to the site owner containing the contents of the form.
No Database
The application does not require a database. No pages are generated using information from a database and no user-submitted data is saved to a database. However, the sqlite3 gem must be present in the Gemfile because Rails ActiveRecord is used for form validation.
Similar 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. Related example applications may be useful:
- Foundation and Rails shows how to integrate Foundation
- Bootstrap and Rails shows to integrate Bootstrap
- OmniAuth and Rails uses OmniAuth for authentication
- Devise and Rails uses Devise for authentication
- Devise and Pundit and Rails uses Pundit for authorization
Accounts You Will Need
The application includes a form that allows website visitors to âopt-inâ to a mailing list. Youâll need a MailChimp account, which is free. MailChimp allows you to send up to 12,000 emails/month to a list of 2000 or fewer subscribers for free. There is no cost to set up an account. After you have set up a MailChimp account, create a new mailing list where you can collect email addresses of visitors who have asked to subscribe to a newsletter. The MailChimp âListsâ page has a button for âCreate List.â The list name and other details are up to you.
With MailChimp, you can send a welcome message automatically when the visitor signs up for the mailing list. Itâs a bit difficult to find the MailChimp option to create a welcome message. Strangely, MailChimp considers a welcome message a âform.â Hereâs how to find it. On the MailChimp âListsâ page, click the âdown arrowâ for a menu and click âSignup forms.â Then click âLink to a form.â On the âCreate Formsâ page, there is a dropdown list of âForms & Response Emails.â The gray box shows âSignup form.â Click the down arrow. Select the menu item named âFinal âWelcomeâ Emailâ and youâll be able to create a welcome message.
To send email from the application, you will need a SendGrid account.
We provide instructions to deploy the tutorial application to Heroku which provides Rails application hosting. It costs nothing to set up a Heroku account and deploy as many applications as you want. To deploy an app to Heroku, you must have a Heroku account. Visit Heroku to set up an account.
Dependencies
Before generating your application, you will need:
- The Ruby language â version 2.4.1
- The Rails gem â version 5.1
See the article Installing Rails for instructions about setting up Rails and your development environment.
Getting the Application
Local
You have several options for getting the code on your own machine. You can fork, clone, or generate.
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/learn-rails.git
Youâll need git on your machine. See Rails and Git.
Generate
If you want to use the project as a starter application, 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 additional options.
To build the example application, Rails 5.1 must be installed in your development environment. Run the command:
$ rails new learn-rails -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb
The $
character indicates a shell prompt; donât include it when you run the command.
The -m
option loads an application template that is hosted on GitHub.
This creates a new Rails app named learn-rails
on your computer. You can use a different name if you wish.
Youâll see a prompt:
option Build a starter application? 1) Build a RailsApps example application 2) Contributed applications 3) Custom application
Enter â1â to select Build a RailsApps example application. Youâll see a prompt:
option Choose a starter application. 1) learn-rails 2) rails-bootstrap 3) rails-foundation 4) rails-mailinglist-activejob 5) rails-omniauth 6) rails-devise 7) rails-devise-roles 8) rails-devise-pundit 9) rails-signup-download 10) rails-stripe-checkout
Choose learn-rails. The Rails Composer tool may give you other options (other applications may have been added since these notes were written).
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.
Troubleshooting
If you get an error âOpenSSL certificate verify failedâ or âGem::RemoteFetcher::FetchError: SSL_connectâ see the article OpenSSL errors and Rails.
README
Edit theIf 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
See the article Installing Rails to make sure your development environment is prepared properly.
RVM
UseI recommend using rvm, the Ruby Version Manager, to create a project-specific gemset for the application. If you generate the application with the Rails Composer tool, you can create a project-specific gemset.
Gems
Here are the gems used by the application:
- foundation-rails â front-end framework
- gibbon â access to the MailChimp API
- high_voltage â for static pages like âaboutâ
- simple_form â forms made easy
These gems make development easier:
- better_errors â helps when things go wrong
- quiet_assets â suppresses distracting messages in the log
- rails_layout â generates files for an application layout
Install the Required Gems
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.
Configuration File
To consolidate configuration settings in a single location, we store credentials in the config/secrets.yml file. To keep your credentials private, use Unix environment variables to set your credentials. See the article Rails Environment Variables for more information.
Add your credentials to the file config/secrets.yml:
# Make sure the secrets in this file are kept private # if you're sharing your code publicly. development: email_provider_username: <%= ENV["SENDGRID_USERNAME"] %> email_provider_password: <%= ENV["SENDGRID_PASSWORD"] %> domain_name: example.com mailchimp_api_key: <%= ENV["MAILCHIMP_API_KEY"] %> mailchimp_list_id: <%= ENV["MAILCHIMP_LIST_ID"] %> owner_email: <%= ENV["OWNER_EMAIL"] %> secret_key_base: very_long_random_string test: secret_key_base: very_long_random_string # Do not keep production secrets in the repository, # instead read values from the environment. production: email_provider_username: <%= ENV["SENDGRID_USERNAME"] %> email_provider_password: <%= ENV["SENDGRID_PASSWORD"] %> domain_name: <%= ENV["DOMAIN_NAME"] %> mailchimp_api_key: <%= ENV["MAILCHIMP_API_KEY"] %> mailchimp_list_id: <%= ENV["MAILCHIMP_LIST_ID"] %> owner_email: <%= ENV["OWNER_EMAIL"] %> secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
All configuration values in the config/secrets.yml file are available anywhere in the application as variables. For example, Rails.application.secrets.email_provider_username
will return the string set in the Unix environment variable SENDGRID_USERNAME
.
To add an environment variable for the MailChimp API key, Log in to MailChimp to get your API key. Click your name at the top of the navigation menu, then click âAccount Settings.â Click âExtras,â then âAPI keys.â
To find the MailChimp list ID, you must have already created a MailChimp mailing list. On the MailChimp âListsâ page, click the âdown arrowâ for a menu and click âSettings.â At the bottom of the âList Settingsâ page, youâll find the unique ID for the mailing list.
The variable domain_name
is used for sending email. You can use example.com
in development. If you already have a custom domain name youâll use when you deploy the application, you can set domain_name
. If you deploy the application to Heroku, youâll set domain_name
with the unique name youâve given your application on Heroku. Youâll have to wait until you deploy to know the name youâll use on Heroku.
Youâll send email messages to the owner_email
address when a visitor submits a contact request form. Set it with an email address where you receive mail.
If you donât want to use Unix environment variables, you can set each value directly in the config/secrets.yml file. The file must be in your git repository when you deploy to Heroku. However, you shouldnât save the file to a public GitHub repository where other people can see your credentials.
Test the App
You can check that your application runs properly by entering the command:
$ rails server
To see your application in action, open a browser window and navigate to http://localhost:3000/.
You should see a home page with a placeholder photo and the âsign upâ form.
Enter your email address and click the âsign upâ button. You should see the page redisplay with an acknowledgment message. Try entering an invalid email address such as âme@fooâ, or click the submit button without entering an email address, and you should see an error message. Youâll have to log in to MailChimp and check your mailing list to see if the new email address was added successfully.
You should be able to click the navigation links for âAboutâ or âContactâ and see those pages.
Submitting the form on the âContactâ page should send an email message to the site ownerâs address.
Stop the server with Control-C. If you test the app by starting the web server and then leave the server running while you install new gems, youâll have to restart the server to see any changes. The same is true for changes to configuration files in the config folder. This can be confusing to new Rails developers because you can change files in the app folders without restarting the server. Stop the server each time after testing and you will avoid this issue.
Deploy to Heroku
Heroku provides low cost, easily configured Rails application hosting.
From the Command Line
You can deploy from the command line.
If youâve set configuration values in the config/secrets.yml file, youâll need to set them as Heroku environment variables. You can set Heroku environment variables directly with heroku config:add
. For example:
$ heroku config:add SENDGRID_USERNAME='example' SENDGRID_PASSWORD='secret' $ heroku config:add MAILCHIMP_API_KEY='my-key' MAILCHIMP_LIST_ID='mylistid' $ heroku config:add OWNER_EMAIL='[email protected]' DOMAIN_NAME='myapp.herokuapp.com'
Complete Heroku deployment with:
$ git push heroku master
See the Tutorial for Rails on Heroku for details.
Where to Get Help
Are you stuck with code that wonât work? Stack Overflow provides a question-and-answer forum for readers of the book. Use the tag ârailsappsâ.
Found a bug in the tutorial application? Please create an issue on GitHub.
Documentation
The book Learn Ruby on Rails provides additional documentation.
Issues
Please create a GitHub issue if you identify any problems or have suggestions for improvements.
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
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
Copyright ©2013-15 Daniel Kehoe