Home > Store

The Rails 5 Way, 4th 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.

Also available in other formats.

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

Description

  • Copyright 2018
  • Dimensions: 7" x 9-1/8"
  • Pages: 1088
  • Edition: 4th
  • eBook
  • ISBN-10: 0-13-465778-0
  • ISBN-13: 978-0-13-465778-3

The “Bible” for Rails Development: Fully Updated for Rails 5

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

—Steve Klabnik, Rails contributor and mentor

The Rails™ 5 Way is the comprehensive, authoritative reference guide for professionals delivering production-quality code using modern Ruby on Rails. Obie Fernandez illuminates the entire Rails 5 API, its most powerful idioms, design approaches, and libraries. He presents new and updated content on Action Cable, RSpec 3.4, Turbolinks 5.0, the Attributes API, and many other enhancements, both major and subtle.

Through detailed code examples, you’ll dive deep into Ruby on Rails, discover why it’s designed as it is, and learn to make it do exactly what you want. Proven in thousands of production systems, the knowledge in this book will maximize your productivity and help you build more successful solutions.

  • Build powerful, scalable, REST-compliant back-end services
  • Program complex program flows using Action Controller
  • Represent models, relationships, and operations in Active Record, and apply advanced Active Record techniques
  • Smoothly evolve database schema via Migrations
  • Craft front-ends with ActionView and the Asset Pipeline
  • Optimize performance and scalability with caching and Turbolinks 5.0
  • Improve your productivity using Haml HTML templating
  • Secure your systems against attacks like SQL Injection, XSS, and XSRF
  • Integrate email using Action Mailer
  • Enable real-time, websockets-based browser behavior with Action Cable
  • Improve responsiveness with background processing
  • Build “API-only” back-end projects that speak JSON
  • Leverage enhancements to Active Job, serialization, and Ajax support


Extras

Author's Site

Please visit the author's sites:
   • http://tr5w.com
   • http://obiefernandez.com
   • kickass-consulting.com

Sample Content

Table of Contents

Foreword by Giles Bowkett xlix

Foreword to the Previous Edition by Steve Klabnik liii

Foreword to the Previous Edition by David Heinemeier Hansson lv

Foreword to the Previous Edition by Yehuda Katz lvii

Introduction lix

Acknowledgments lxv

About the Author lxvii

Chapter 1: Rails Configuration and Environments 1

1.1 Bundler 2

1.2 Startup Scripts 10

1.3 Default Initializers 12

1.4 Other Common Initializers 19

1.5 Spring Application Preloader 21

1.6 Development Mode 22

1.7 Test Mode 27

1.8 Production Mode 29

1.9 Configuring a Database 32

1.10 Configuring Application Secrets 33

1.11 Logging 34

1.12 Conclusion 41

Chapter 2: Routing 43

2.1 The Two Purposes of Routing 44

2.2 The routes.rb File 45

2.3 Route Globbing 57

2.4 Named Routes 58

2.5 Scoping Routing Rules 63

2.6 Listing Routes 66

2.7 Conclusion 66

Chapter 3: REST, Resources, and Rails 69

3.1 REST in a Rather Small Nutshell 70

3.2 Resources and Representations 71

3.3 REST in Rails 71

3.4 Routing and CRUD 72

3.5 The Standard RESTful Controller Actions 76

3.6 Singular Resource Routes 80

3.7 Nested Resources 80

3.8 Routing Concerns 85

3.9 RESTful Route Customizations 86

3.10 Controller-Only Resources 91

3.11 Different Representations of Resources 93

3.12 The RESTful Rails Action Set 95

3.13 Conclusion 100

Chapter 4: Working with Controllers 101

4.1 Rack 102

4.2 Action Dispatch: Where It All Begins 105

4.3 Render unto View . . . 108

4.4 Additional Layout Options 120

4.5 Redirecting 121

4.6 Controller/View Communication 124

4.7 Action Callbacks 125

4.8 Streaming 131

4.9 Variants 138

4.10 Conclusion 139

Chapter 5: Working with Active Record 141

5.1 The Basics 142

5.2 Macro-Style Methods 143

5.3 Defining Attributes 146

5.4 CRUD: Creating, Reading, Updating, Deleting 149

5.5 Database Locking 162

5.6 Querying 166

5.7 Ignoring Columns 185

5.8 Connections to Multiple Databases in Different Models 186

5.9 Using the Database Connection Directly 187

5.10 Custom SQL Queries 191

5.11 Other Configuration Options 193

5.12 Conclusion 194

Chapter 6: Active Record Migrations 195

6.1 Creating Migrations 195

6.2 Defining Columns 207

6.3 Transactions 214

6.4 Data Migration 214

6.5 Database Schema 218

6.6 Database Seeding 219

6.7 Database-Related Tasks 220

6.8 Conclusion 224

Chapter 7: Active Record Associations 225

7.1 The Association Hierarchy 225

7.2 One-to-Many Relationships 226

7.3 Belongs to Associations 227

7.4 Has Many Associations 238

7.5 Many-to-Many Relationships 253

7.6 One-to-One Relationships 266

7.7 Working with Unsaved Objects and Associations 270

7.8 Association Extensions 272

7.9 The CollectionProxy Class 274

7.10 Conclusion 275

Chapter 8: Validations 277

8.1 Finding Errors 277

8.2 The Simple Declarative Validations 278

8.3 Common Validation Options 289

8.4 Conditional Validation 291

8.5 Short-Form Validation 293

8.6 Custom Validation Techniques 294

8.7 Skipping Validations 297

8.8 Working with the Errors Hash 298

8.9 Testing Validations with Shoulda 298

8.10 Conclusion 299

Chapter 9: Advanced Active Record 301

9.1 Scopes 302

9.2 Callbacks 306

9.3 Attributes API 317

9.4 Serialized Attributes 325

9.5 Enums 329

9.6 Generating Secure Tokens 331

9.7 Calculation Methods 333

9.8 Batch Operations 334

9.9 Single-Table Inheritance (STI) 344

9.10 Abstract Base Model Classes 351

9.11 Polymorphic has_many Relationships 352

9.12 Foreign-Key Constraints 355

9.13 Modules for Reusing Common Behavior 359

9.14 Value Objects 363

9.15 Non-persisted Models 366

9.16 Modifying Active Record Classes at Runtime 368

9.17 PostgreSQL 371

9.18 Conclusion 376

Chapter 10: Action View 377

10.1 Layouts and Templates 378

10.2 Partials 387

10.3 Conclusion 393

Chapter 11: All about Helpers 395

11.1 ActiveModelHelper 395

11.2 AssetTagHelper 396

11.3 AssetUrlHelper 400

11.4 AtomFeedHelper 406

11.5 CacheHelper 408

11.6 CaptureHelper 408

11.7 ControllerHelper 410

11.8 CsrfHelper 410

11.9 DateHelper 411

11.10 DebugHelper 418

11.11 FormHelper 418

11.12 FormOptionsHelper 438

11.13 FormTagHelper 446

11.14 JavaScriptHelper 452

11.15 NumberHelper 453

11.16 OutputSafetyHelper 457

11.17 RecordTagHelper 458

11.18 RenderingHelper 459

11.19 SanitizeHelper 459

11.20 TagHelper 461

11.21 TextHelper 463

11.22 TranslationHelper and the I18n API 467

11.23 UrlHelper 487

11.24 Writing Your Own View Helpers 492

11.25 Wrapping and Generalizing Partials 495

11.26 Conclusion 501

Chapter 12: Haml 503

12.1 Getting Started 504

12.2 The Basics 504

12.3 Doctype 509

12.4 Comments 509

12.5 Evaluating Ruby Code 510

12.6 Helpers 513

12.7 Filters 514

12.8 Haml and Content 515

12.9 Configuration Options 516

12.10 Conclusion 518

Chapter 13: Session Management 519

13.1 What to Store in the Session 520

13.2 Storage Mechanisms 521

13.3 Cookies 524

13.4 Conclusion 526

Chapter 14: Authentication and Authorization 527

14.1 Warden 527

14.2 Devise 531

14.3 has_secure_password 544

14.4 Pundit 549

14.5 Conclusion 555

Chapter 15: Security 557

15.1 Password Management 558

15.2 Log Masking 560

15.3 SSL (Secure Sockets Layer) 560

15.4 Model Mass-Assignment Attributes Protection 561

15.5 SQL Injection 564

15.6 Cross-Site Scripting (XSS) 566

15.7 XSRF (Cross-Site Request Forgery) 569

15.8 Session Fixation Attacks 572

15.9 Keeping Secrets 572

15.10 Conclusion 574

Chapter 16: Action Mailer 575

16.1 Mailer Models 575

16.2 Previews 585

16.3 Receiving Emails 587

16.4 Testing Email Content 589

16.5 Sending via API 590

16.6 Configuration 591

16.7 Conclusion 592

Chapter 17: Caching and Performance 593

17.1 View Caching 593

17.2 Data Caching 610

17.3 Control of Web Caching 612

17.4 ETags 614

17.5 Conclusion 615

Chapter 18: Background Processing 617

18.1 Active Job 617

18.2 Queueing Backends 622

18.3 Rails Runner 634

18.4 Conclusion 636

Chapter 19: Asset Pipeline 637

19.1 Introduction to Asset Management 638

19.2 Organization. Where Does Everything Go? 639

19.3 Manifest Files 640

19.4 Custom Format Handlers 645

19.5 Post-Processing 646

19.6 Helpers 647

19.7 Fingerprinting 649

19.8 Serving the Files 650

19.9 Rake Tasks 653

19.10 Yarn 654

19.11 Webpack 656

19.12 Conclusion 660

Chapter 20: Ajax on Rails 661

20.1 Unobtrusive JavaScript 662

20.2 Ajax and JSON 666

20.3 Ajax and HTML 668

20.4 JSONP Requests 669

20.5 Conclusion 671

Chapter 21: Turbolinks 673

21.1 Turbolinks Usage 674

21.2 Building Your Turbolinks Application 676

21.3 Understanding Turbolinks Caching 677

21.4 Making Transformations Idempotent 679

21.5 Responding to Page Updates 679

21.6 Persisting Elements across Page Loads 680

21.7 Advanced Turbolinks 681

21.8 Turbolinks API Reference 683

21.9 Turbolinks Events 684

21.10 Conclusion 685

Chapter 22: Action Cable 687

22.1 Web Sockets 687

22.2 Publish-Subscribe Pattern 688

22.3 Connections 688

22.4 Channels 689

22.5 Subscriptions 690

22.6 Streams 691

22.7 Subscriptions Revisited (Browser-Side) 691

22.8 Rebroadcasting 691

22.9 Channel Actions 692

22.10 Configuration 694

22.11 Running Stand-Alone Cable Servers 696

22.12 Generator 696

22.13 Conclusion 697

Chapter 23: RSpec 699

23.1 Introduction 699

23.2 Behavior-Driven Development 700

23.3 Basic Syntax and API 702

23.4 Custom Expectation Matchers 716

23.5 Helper Methods 719

23.6 Shared Behaviors 720

23.7 Shared Context 721

23.8 Mocks and Stubs 721

23.9 Running Specs 724

23.9.2 Filtering 726

23.10 Factory Girl 726

23.11 RSpec and Rails 738

23.12 Feature Specs with Capybara 752

23.13 Working with Files in Your Specs 754

23.14 RSpec Tools 755

23.15 Conclusion 758

Appendix A: Active Model API Reference 761

A.1 AttributeAssignment 761

A.2 AttributeMethods 762

A.3 Callbacks 764

A.4 Conversion 766

A.5 Dirty 766

A.6 Errors 769

A.7 ForbiddenAttributesError 774

A.8 Lint::Tests 775

A.9 MissingAttributeError 776

A.10 Model 776

A.11 Name 778

A.12 Naming 780

A.13 SecurePassword 781

A.14 Serialization 781

A.15 Serializers::JSON 782

A.16 Translation 784

A.17 Type 785

A.18 ValidationError 786

A.19 Validations 786

A.20 Validator 792

Appendix B: Active Support API Reference 795

B.1 Array 796

B.2 Autoload 803

B.3 BacktraceCleaner 805

B.4 Benchmark 806

B.5 Benchmarkable 806

B.6 BigDecimal 807

B.7 Cache::FileStore 807

B.8 Cache::MemCacheStore 808

B.9 Cache::MemoryStore 808

B.10 Cache::NullStore 809

B.11 Cache::Store 809

B.12 CachingKeyGenerator 814

B.13 Callbacks 815

B.14 Class 817

B.15 Concern 820

B.16 Configurable 821

B.17 Date 821

B.18 DateAndTime 831

B.19 DateTime 834

B.20 Dependencies 838

B.21 DescendantsTracker 843

B.22 Digest::UUID 843

B.23 Duration 844

B.24 Enumerable 846

B.25 ERB::Util 847

B.26 EventedFileUpdateChecker 848

B.27 FalseClass 849

B.28 File 849

B.29 FileUpdateChecker 849

B.30 Gzip 851

B.31 Hash 851

B.32 HashWithIndifferentAccess 857

B.33 Inflector 858

B.34 Inflector::Inflections 858

B.35 Integer 862

B.36 JSON 863

B.37 Kernel 863

B.38 KeyGenerator 864

B.39 LazyLoadHooks 865

B.40 Locale 866

B.41 LogSubscriber 869

B.42 Logger 870

B.43 MessageEncryptor 871

B.44 MessageVerifier 872

B.45 Module 872

B.46 Module::Concerning 879

B.47 Multibyte::Chars 880

B.48 Multibyte::Unicode 883

B.49 NameError 884

B.50 NilClass 885

B.51 Notifications 886

B.52 NumberHelper 889

B.53 Numeric 890

B.54 Object 898

B.55 OrderedOptions 904

B.56 ProxyObject 904

B.57 Railtie 905

B.58 Range 906

B.59 Regexp 907

B.60 Rescuable 907

B.61 SecureRandom 909

B.62 SecurityUtils 909

B.63 String 909

B.64 StringInquirer 918

B.65 Subscriber 919

B.66 TaggedLogging 919

B.67 TestCase 919

B.68 Testing::Assertions 921

B.69 Thread 924

B.70 Time 925

B.71 TimeWithZone 935

B.72 TimeZone 936

B.73 TrueClass 940

B.74 XmlMini 940

Appendix C: Rails API 943

C.1 Rails API Mode 944

C.2 JSON 945

Index 951

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