Home > Store

Rails 4 Way, The, 3rd Edition

Register your product to gain access to bonus material or receive a coupon.

Rails 4 Way, The, 3rd Edition

eBook

  • Your Price: $38.39
  • List Price: $47.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

Description

  • Copyright 2014
  • Dimensions: 7" x 9-1/8"
  • Pages: 880
  • Edition: 3rd
  • eBook
  • ISBN-10: 0-13-348794-6
  • ISBN-13: 978-0-13-348794-7

The “Bible” for Rails Development: Now Fully Updated for Rails 4.1

"When I read The Rails Way for the first time, I felt like I truly understood Rails for the first time.”

—From the Foreword by Steve Klabnik

Ruby on Rails 4 is leaner, tighter, and even more valuable to professional web developers. More than ever, it helps you focus on what matters most: delivering business value via clean and maintainable code.

The Rails 4 Way is the only comprehensive, authoritative guide to delivering production-quality code with Rails 4. Kevin Faustino joins pioneering Rails developer Obie Fernandez to illuminate the entire Rails 4 API, including its most powerful and modern idioms, design approaches, and libraries. They present extensive new and updated content on security, performance, caching, Haml, RSpec, Ajax, the Asset Pipeline, and more.

Through detailed code examples, you’ll dive deep into the Rails 4 code base, discover why Rails is designed as it is, and learn how to make it do exactly what you want. Proven in dozens of production systems, this book’s techniques will maximize your productivity and help you build more successful solutions. You’ll want to keep this guide by your computer—you’ll refer to it constantly.

This guide will help you

  • Build powerful, scalable REST-compliant APIs
  • Program complex program flows using Action Controller
  • Represent models, relationships, CRUD operations, searches, validation, callbacks, and more
  • Smoothly evolve application database schema via Migrations
  • Apply advanced Active Record techniques: single-table inheritance, polymorphic models, and more
  • Create visual elements with Action View and partials
  • Optimize performance and scalability with view caching
  • Master the highly productive Haml HTML templating engine
  • Make the most of Rails’ approach to session management
  • Secure your systems with Rails 4’s improved authentication and authorization
  • Resist SQL Injection, XSS, XSRF, and other attacks
  • Extend Rails with popular gems and plugins, and learn to write your own
  • Integrate email services with Action Mailer
  • Use Ajax via Rails 4 support for unobtrusive JavaScript
  • Improve responsiveness with background processing
  • Leverage Asset Pipeline to simplify development, improve perceived performance, and reduce server burdens
  • Accelerate implementation and promote maintainability with RSpec

Sample Content

Table of Contents

Foreword by Steve Klabnik xxxix

Foreword to the Previous Edition by David Heinemeier Hansson xli

Foreword to the Previous Edition by Yehuda Katz xliii

Introduction xlv

Acknowledgments li

About the Authors liii

 

Chapter 1: Rails Environments and Configuration 1

1.1 Bundler 2

1.2 Startup and Application Settings 9

1.3 Development Mode 18

1.4 Test Mode 22

1.5 Production Mode 23

1.6 Configuring a Database 26

1.7 Configuring Application Secrets 27

1.8 Logging 29

1.9 Conclusion 35

Chapter 2: Routing 37

2.1 The Two Purposes of Routing 38

2.2 The routes.rb File 39

2.3 Route Globbing 51

2.4 Named Routes 53

2.5 Scoping Routing Rules 57

2.6 Listing Routes 60

2.7 Conclusion 61

Chapter 3: REST, Resources, and Rails 63

3.1 REST in a Rather Small Nutshell 63

3.2 Resources and Representations 64

3.3 REST in Rails 65

3.4 Routing and CRUD 66

3.5 The Standard RESTful Controller Actions 69

3.6 Singular Resource Routes 73

3.7 Nested Resources 74

3.8 Routing Concerns 78

3.9 RESTful Route Customizations 79

3.10 Controller-Only Resources 83

3.11 Different Representations of Resources 86

3.12 The RESTful Rails Action Set 88

3.13 Conclusion 92

Chapter 4: Working with Controllers 95

4.1 Rack 96

4.2 Action Dispatch: Where It All Begins 99

4.3 Render unto View… 102

4.4 Additional Layout Options 111

4.5 Redirecting 111

4.6 Controller/View Communication 115

4.7 Action Callbacks 116

4.8 Streaming 121

4.9 Variants 126

4.10 Conclusion 127

Chapter 5: Working with Active Record 129

5.1 The Basics 130

5.2 Macro-Style Methods 131

5.3 Defining Attributes 133

5.4 CRUD: Create, Read, Update, and Delete 138

5.5 Database Locking 151

5.6 Where Clauses 155

5.7 Connections to Multiple Databases in Different Models 165

5.8 Using the Database Connection Directly 167

5.9 Other Configuration Options 171

5.10 Conclusion 171

Chapter 6: Active Record Migrations 173

6.1 Creating Migrations 173

6.2 Data Migration 187

6.3 schema.rb 189

6.4 Database Seeding 190

6.5 Database-Related Rake Tasks 191

6.6 Conclusion 194

Chapter 7: Active Record Associations 195

7.1 The Association Hierarchy 195

7.2 One-to-Many Relationships 196

7.3 The belongs_to Association 205

7.4 The has_many Association 214

7.5 Many-to-Many Relationships 222

7.6 One-to-One Relationships 233

7.7 Working with Unsaved Objects and Associations 236

7.8 Association Extensions 238

7.9 The CollectionProxy Class 239

7.10 Conclusion 240

Chapter 8: Validations 241

8.1 Finding Errors 241

8.2 The Simple Declarative Validations 242

8.3 Common Validation Options 253

8.4 Conditional Validation 255

8.5 Short-Form Validation 256

8.6 Custom Validation Techniques 258

8.7 Skipping Validations 260

8.8 Working with the Errors Hash 261

8.9 Testing Validations with Shoulda 262

8.10 Conclusion 262

Chapter 9: Advanced Active Record 263

9.1 Scopes 263

9.2 Callbacks 268

9.3 Calculation Methods 278

9.4 Single-Table Inheritance (STI) 280

9.5 Abstract Base Model Classes 286

9.6 Polymorphic has_many Relationships 287

9.7 Enums 290

9.8 Foreign-Key Constraints 292

9.9 Modules for Reusing Common Behavior 292

9.10 Modifying Active Record Classes at Runtime 297

9.11 Using Value Objects 299

9.12 Nonpersisted Models 302

9.13 PostgreSQL Enhancements 304

9.14 Conclusion 311

Chapter 10: Action View 313

10.1 Layouts and Templates 314

10.2 Partials 322

10.3 Conclusion 329

Chapter 11: All about Helpers 331

11.1 ActiveModelHelper 331

11.2 AssetTagHelper 338

11.3 AtomFeedHelper 346

11.4 CacheHelper 348

11.5 CaptureHelper 348

11.6 CsrfHelper 349

11.7 DateHelper 349

11.8 DebugHelper 356

11.9 FormHelper 357

11.10 FormOptionsHelper 371

11.11 FormTagHelper 379

11.12 JavaScriptHelper 385

11.13 NumberHelper 385

11.14 OutputSafetyHelper 390

11.15 RecordTagHelper 390

11.16 RenderingHelper 391

11.17 SanitizeHelper 391

11.18 TagHelper 393

11.19 TextHelper 395

11.20 TranslationHelper and the I18n API 399

11.21 UrlHelper 418

11.22 Writing Your Own View Helpers 422

11.23 Wrapping and Generalizing Partials 425

11.24 Conclusion 431

Chapter 12: Haml 433

12.1 Getting Started 434

12.2 The Basics 434

12.3 Doctype 440

12.4 Comments 440

12.5 Evaluating Ruby Code 441

12.6 Helpers 443

12.7 Filters 444

12.8 Haml and Content 445

12.9 Configuration Options 446

12.10 Conclusion 448

Chapter 13: Session Management 449

13.1 What to Store in the Session 450

13.2 Session Options 451

13.3 Storage Mechanisms 451

13.4 Cookies 455

13.5 Conclusion 457

Chapter 14: Authentication and Authorization 459

14.1 Devise 459

14.2 has_secure_password 466

14.3 Pundit 470

14.4 Conclusion 476

Chapter 15: Security 477

15.1 Password Management 477

15.2 Log Masking 479

15.3 SSL (Secure Sockets Layer) 480

15.4 Model Mass-Assignment Attributes Protection 481

15.5 SQL Injection 483

15.6 Cross-Site Scripting (XSS) 484

15.7 XSRF (Cross-Site Request Forgery) 487

15.8 Session Fixation Attacks 490

15.9 Keeping Secrets 491

15.10 Conclusion 492

Chapter 16: Action Mailer 493

16.1 Setup 493

16.2 Mailer Models 494

16.3 Receiving Emails 500

16.4 Server Configuration 502

16.5 Testing Email Content 502

16.6 Previews 503

16.7 Conclusion 504

Chapter 17: Caching and Performance 505

17.1 View Caching 505

17.2 Data Caching 521

17.3 Control of Web Caching 523

17.4 ETags 524

17.5 Conclusion 526

Chapter 18: Background Processing 527

18.1 Delayed Job 528

18.2 Sidekiq 531

18.3 Resque 537

18.4 Rails Runner 541

18.5 Conclusion 543

Chapter 19: Ajax on Rails 545

19.1 Unobtrusive JavaScript 547

19.2 Turbolinks 551

19.3 Ajax and JSON 553

19.4 Ajax and HTML 555

19.5 Ajax and JavaScript 557

19.6 Conclusion 558

Chapter 20: Asset Pipeline 559

20.1 Asset Pipeline 560

20.2 Wish List 560

20.3 The Big Picture 561

20.4 Organization: Where Does Everything Go? 561

20.5 Manifest Files 561

20.6 Custom Format Handlers 567

20.7 Postprocessing 568

20.8 Helpers 569

20.9 Fingerprinting 571

20.10 Serving the Files 572

20.11 Rake Tasks 573

20.12 Conclusion 574

Chapter 21: RSpec 575

21.1 Introduction 575

21.2 Basic Syntax and API 578

21.3 Matchers 587

21.4 Custom Expectation Matchers 588

21.5 Shared Behaviors 591

21.6 Shared Context 592

21.7 RSpec’s Mocks and Stubs 592

21.8 Running Specs 595

21.9 RSpec Rails Gem 596

21.10 RSpec Tools 609

21.11 Conclusion 610

Chapter 22: XML 611

22.1 The to_xml Method 611

22.2 The XML Builder 620

22.3 Parsing XML 622

22.4 Conclusion 624

Appendix A: Active Model API Reference 625

A.1 AttributeMethods 625

A.2 Callbacks 627

A.3 Conversion 629

A.4 Dirty 629

A.5 Errors 631

A.6 ForbiddenAttributesError 635

A.7 Lint::Tests 635

A.8 Model 635

A.9 Name 636

A.10 Naming 638

A.11 SecurePassword 638

A.12 Serialization 638

A.13 Serializers::JSON 639

A.14 Serializers::Xml 639

A.15 Translation 640

A.16 Validations 641

A.17 Validator 648

Appendix B: Active Support API Reference 651

B.1 Array 651

B.2 ActiveSupport::BacktraceCleaner 657

B.3 Benchmark 658

B.4 ActiveSupport::Benchmarkable 658

B.5 BigDecimal 659

B.6 ActiveSupport::Cache::Store 660

B.7 ActiveSupport::CachingKeyGenerator 665

B.8 ActiveSupport::Callbacks 665

B.9 Class 668

B.10 ActiveSupport::Concern 671

B.11 ActiveSupport::Concurrency 672

B.12 ActiveSupport::Configurable 673

B.13 Date 673

B.14 DateTime 682

B.15 ActiveSupport::Dependencies 687

B.16 ActiveSupport::Deprecation 693

B.17 ActiveSupport::DescendantsTracker 694

B.18 ActiveSupport::Duration 695

B.19 Enumerable 696

B.20 ERB::Util 697

B.21 FalseClass 698

B.22 File 698

B.23 Hash 699

B.24 ActiveSupport::Gzip 704

B.25 ActiveSupport::HashWithIndifferentAccess 705

B.26 ActiveSupport::Inflector::Inflections 705

B.27 Integer 711

B.28 ActiveSupport::JSON 712

B.29 Kernel 712

B.30 ActiveSupport::KeyGenerator 714

B.31 ActiveSupport::Logger 714

B.32 ActiveSupport::MessageEncryptor 715

B.33 ActiveSupport::MessageVerifier 715

B.34 Module 716

B.35 ActiveSupport::Multibyte::Chars 724

B.36 NilClass 729

B.37 ActiveSupport::Notifications 729

B.38 Object 738

B.39 ActiveSupport::OrderedHash 743

B.40 ActiveSupport::OrderedOptions 743

B.41 ActiveSupport::PerThreadRegistry 744

B.42 ActiveSupport::ProxyObject 744

B.43 ActiveSupport::Railtie 745

B.44 Range 746

B.45 Regexp 747

B.46 ActiveSupport::Rescuable 748

B.47 String 748

B.48 ActiveSupport::StringInquirer 758

B.49 Struct 758

B.50 ActiveSupport::Subscriber 758

B.51 Symbol 759

B.52 ActiveSupport::TaggedLogging 759

B.53 ActiveSupport::TestCase 759

B.54 ActiveSupport::Testing::Assertions 761

B.55 Thread 762

B.56 Time 763

B.57 ActiveSupport::TimeWithZone 773

B.58 ActiveSupport::TimeZone 774

B.59 TrueClass 778

B.60 ActiveSupport::XmlMini 778

Appendix C: Rails Essentials 781

C.1 Environmental Concerns 781

C.2 Essential Gems 782

C.3 Ruby Toolbox 789

C.4 Screencasts 789

Index 791

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020