by Michael Hartl
- The "rails root" is the root directory for any given application, and is not the root directory for Rails itself.
- Since gems with different version numbers sometimes conflict, it is often convenient to create separate gemsets, which are self-contained bundles of gems.
- The
appsubdirectory contains all models, views, controllers, and helpers. - The
Gemfilelists Gem requirements for an app, whileGemfile.lockis a list of gems used to ensure that all copies of the app use the same gem versions. - Unless you specify a version number to the gem command in a
Gemfile, Bundler will automatically install the latest version, which may cause minor breakage. - The
>=notation always performs upgrades, whereas the~>notation only performs upgrades to minor point releases but not to major point releases. - After assembling the Gemfile, install the gems by running
bundle install. - Running the
rails servercommand, or its shortcutrails s, will run a local development web server. - Using
git commit -acommits all modifications to existing files or files created usinggit mv, which don't count as new files to Git.
- If a gem is intended for production with
group: productionin yourGemfile, you can skip installing it locally by runningbundle install --without production. - To use the version of Rake corresponding to your Gemfile, run it using
bundle exec, for examplebundle exec rake db:migrate. - The
POST,PUT, andDELETEmethods are routed to thecreate,update, anddestroyactions, and unlike the other actions do not render pages. - In a one-to-many relationship, the model on the one-side uses
has_many, while the model on the many-side usesbelongs_to.
- Passing the
--skip-unit-testoption to therails newcommand will skip generating a test directory associated with theTest::Unitframework. - The Capybara gem allows you to simulate a user's interaction with an application using a natural English-like syntax.
- The
--without productionoption passed tobundle installis a remembered option, and so can be omitted on future invocations. - Any files in the
publicdirectly are served directly from the filesystem and don't even hit the Rails stack. - After using
rails generate rspec:installto usegeneratewith RSpec, passing--no-test-frameworktorails generatewill suppress generating default RSpec tests. - Web browsers are incapable of sending
PUTandDELETEmethods natively, but web frameworks like Rails make it seem like browsers are issuing such requests. - The TDD practice of writing a failing test, making it pass, and then cleaning up is called "red, green, refactor."
- The
have_selectormethod performs a partial match given whatever string is mapped to by:textin the given hash. - In embedded Ruby,
<% ... %>executes the code inside, while<%= ... %>executes the code and inserts the result into the template. - Calling
<%= yield %>in the special layout fileapplication.html.erbinserts the content of the page into the layout; other values are passed usingprovide.
- Functions for use in views are called helpers, and are found in the
app/helpersdirectory. - The Rails console, accessed with
rails consoleorrails c, is built on top of interactive ruby, orirb. - The
putsmethod appends a newline character\nto the output, while theprintmethod does not. - Single-quoted strings are truly literal, and so do not interpolate values using the
#{}syntax, and do not form escape sequences. - Any method that returns a boolean ends with
?. - The
nilobject is the only Ruby object that is false in a boolean context, apart fromfalseitself. Even0is true. - The
includestatement mixes in a module. Rails automatically mixes theApplicationHelperinto all views so its methods are available everywhere. - Bang methods, which end with
!, mutate a value instead of returning a different value. - For blocks, it is typical to use curly braces only for short one-line blocks, and the
do ... endsyntax for anything longer. - It is a convention to put an extra space at the two ends of a hash literal, and spaces around each "hashrocket", or
=>. - When using symbols as hash keys, the symbol/hashrocket combination can be replaced with the key name followed by a colon and a value.
- The
inspectmethod returns the string literal for an object, and the shortcutpfunction is equivalent to callinginspecton its argument and usingputs. - When a hash is the last argument in a function call, its curly braces are optional.
- While
array.newtakes an initial value for the array,Hash.newtakes a default value for the hash. - The
blank?method, added to theStringclass by Rails, returns whether a string is composed entirely of whitespace. - A Rails convention is to pass a hash named
attributesinto theinitializemethod, or constructor, of a class.
- The
altattribute is passed in the optional options hash to theimage_taghelper, but is in fact required by the HTML standard. - The
bootstrap-sassgem converts the LESS used by Bootstrap to the Sass language used by Rails. - Filenames of partials start with an underscore, but are omitted in the call to
render. Shared partials are found in theapp/views/layoutsdirectory. - Static assets specific to the application are in
app/assets; assets for libraries written by your dev team are inlib/assets; and assets from third-party vendors are invendor/assets. - Filename extensions of assets specify which preprocessor engines to use; if multiple are specified, the associated preprocessors are run from right to left.
- The asset pipeline puts all CSS in one
application.cssfile, all Javascript in onejavascripts.jsfile, and minimizes assets in all paths where possible. - The
bootstrap-sassgem provides Sass equivalents of all the LESS variables for colors found in Bootstrap. - A named route ending with
_pathis just the pathname, while the one ending with_urlincludes the hostname and scheme. - It's convention to route the root of your site using
rootinstead ofmatch '/'. - Files included in the
spec/supportdirectory are automatically included by RSpec. - If you just run
rakeby itself, the default behavior is to run the full test suite.
- In contrast to the plural convention for controller names, model names are singular, although the underlying table name is in the plural form.
- For an irreversible database migration like removing a database column, you must define separate
self.upandself.downmethods in place of thechangemethod. - The
annotategem precedes each model definition with a comment containing its field names and types. - By default all model attributes are accessible, but
attr_accessibleensures that only the provided attributes are accessible to outside users. - Starting
rails consolewith the--sandboxflag rolls back any changes on exit. - The
createmethod combines thenewandsaveactions into one. - The
update_attributemethod combines both theupdateandsaveactions into one, but can only modify those attributes defined as accessible usingattr_accessible. - The
db:test:prepareRake task ensures that the data model from the development databasedb/development.sqlite3is reflected in the test databasedb/test.sqlite3. - In RSpec, whenever an object responds to a boolean method
foo?, there is a corresponding test method calledbe_foo. - Constants in Ruby have a name that starts with a capital letter.
- Using
validates: uniquenessis a query-then-write approach subject to race conditions; to properly enforce uniqueness, use an index at the the database level. - Not all database adapters use case-insensitive indices, and so you must use a database callback to lowercase a string before writing it.
- When using
rails generate migration, to automatically create a migration for tabletablename, end the migration name with_to_tabename. - If the password confirmation field is
nil, Rails doesn't run the confirmation validation, although this can never happen on the web, and only through the console. - The
letmethod in RSpec memoizes its value, and so the value is remembered from one invocation to the next. - Given a
password_digestcolumn in the database, thehas_secure_passwordmethod provides a secure way to create and authenticate new users.
- The
consolecommand accepts the environment as an argument,serverthrough the--environmentflag, anddb:migratethrough theRAILS_ENVvariable. - To speed up your tests, redefine the BCrypt cost factor in
config/environments/test.rbfrom its secure default value to its fast minimum value. - Methods defined in any helper file are automatically available in any view, but strive for organization and convenience.
- To reset the database, use the
db:resetRake task. This may need to be followed with thedb:test:prepareRake task before testing. - The
countmethod on every Active Record class and thechangemethod in RSpec can be used to verify that validations stopped a write from succeeding. - Passing
-eand a string to RSpec runs just the tests whose description strings match the given string. - To display an empty form using
form_for, simply create an empty Active Record object in the corresponding controller. - Partials expected to be used in views across multiple controllers should be placed in the
app/views/shareddirectory. - The
any?method is the opposite ofempty?, returningtrueif an array is not empty, andfalseif it is. - The
pluralizemethod inActionView::Helpers::TextHelperis backed by a powerful inflector that can pluralize almost any word. - The
redirect_tomethod can construct a RESTful URL from any Active Record object passed as a parameter. - The
flashvariable is like a special hash whose values disappear upon visiting a second page or upon reloading. - Embedded Ruby will automatically convert symbols into strings before inserting them into the template.
- To change the names of fields with missing values in error messages, edit the corresponding attribute in
config/locales/en.yml. - The
content_taghelper method can improve readability wherever ERb is used to compute HTML attributes inside quotes.
- Modeling sessions as a RESTful resource, signing in is a
POSTrequest to thecreateaction, and signing out is aDELETErequest to thedestroyaction. - Passing the
onlyoption toresourcesinconfig/routes.rbrestricts the RESTful routes generated. - If you cannot provide a suitable model for
form_for, you can pass the name of the resource and the corresponding URI as parameters. - Display error messages on rendered pages using
flash.nowbecause its contents disappear upon an additional request; when using redirects, useflash. - By default, helpers are available in views, but you must use
includeto make them available in controllers. - Values stored in the
sessionobject are stored in a cookie that expires upon the browser closing. - The
itsmethod of RSpec applies the subsequent test to the given attribute rather than the subject of the test. - Inside private methods called by a model's
before_savemethod, column names that are written to must be preceded byself. - The
permanentmethod ofcookiesis a shortcut for setting the optional expires date of a value to 20 years in the future, or20.years.from_now.utc. - The
||=operator can be used to assign a value to a variable if it is currently undefined. - Passing
validate: falsetosaveskips the validations for the model, which is useful inrails console. - File
spec/support/utilities.rbcan contain not just helper methods but custom matchers (likehave_selectororhave_link) usingRSpec::Matchers.define.