Page
1
(This page has no text content)
Page
2
Growing Rails Applications in Practice Structure large Ruby on Rails apps with the tools you already know and love Henning Koch and Thomas Eisenbarth This book is for sale at http://leanpub.com/growing-rails This version was published on 2014-06-20 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. ©2013 - 2014 makandra GmbH
Page
3
Contents 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 How we got here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 The myth of the infinitely scalable architecture . . . . . . . . . . . . . . . . . . . . . . . . 1 How we structured this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 New rules for Rails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2 Beautiful controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 The case for consistent controller design . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Normalizing user interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 A better controller implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Why have controllers at all? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3 Relearning ActiveRecord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Understanding the ActiveRecord lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 The true API of ActiveRecord models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 4 User interactions without a database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Writing a better sign in form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Building PlainModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Refactoring controllers from hell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Creating a system for growth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 5 Dealing with fat models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Why models grow fat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 The case of the missing classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Getting into a habit of organizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 6 A home for interaction-specific code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 A modest approach to form models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 More convenience for form models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 7 Extracting service objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Page
4
CONTENTS Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Did we just move code around? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 8 Organizing large codebases with namespaces . . . . . . . . . . . . . . . . . . . . . . . 44 Real-world example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Use the same structure everywhere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 9 Taming stylesheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 How CSS grows out of control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 An API for your stylesheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 The BEM prime directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Full BEM layout example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Organizing stylesheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 BEM anti-patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Living style guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Pragmatic BEM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Building applications to last . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 10 On following fashions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Before/after code comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Understanding trade-offs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 The value of consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 11 Surviving the upgrade pace of Rails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Gems increase the cost of upgrades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Upgrades are when you pay for monkey patches . . . . . . . . . . . . . . . . . . . . . . . 72 Don’t live on the bleeding edge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 12 Owning your stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Accepting storage services into your stack . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Maxing out your current toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 13 The value of tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Choosing test types effectively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 How many tests are too many? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 When to repeat yourself in tests - and when not to . . . . . . . . . . . . . . . . . . . . . . 80 Better design guided by tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Getting started with tests in legacy applications . . . . . . . . . . . . . . . . . . . . . . . . 81 Overcoming resistance to testing in your team . . . . . . . . . . . . . . . . . . . . . . . . 81 14 Closing thoughts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Page
5
1 Introduction In this book we demonstrate low-ceremony techniques to scale large, monolithic Rails applications. Instead of introducing new patterns or service-oriented architecture, we will show how to use discipline, consistency and code organization to make your code grow more gently. Instead of using new gems we will use the tools built into Rails to accomplish our goal. The tools you already know and love. How we got here When you started working with Rails some years ago, it all seemed so easy. You saw the blog-in- ten-minutes video. You reproduced the result. ActiveRecord felt great and everything had its place. Fast forward two years. Your blog is now a full-blown CMS with a hundred models and controllers. Your team has grown to four developers. Every change to the application is a pain. Your code feels like a house of cards. You turn to the internet for assistance, and find it filled with silver bullets. You should move away from fat controllers, it says. But do avoid fat models. And use DCI. Or CQRS. Or SOA. As you cycle through patterns, your application is becoming a patchwork of different coding techniques. New team members are having a hard time catching up. And you are beginning to question if all those new techniques actually help, or if you are just adding layers of indirection. You start missing the early days, when everything had seemed so easy and every new piece of code had its place. You actually liked ActiveRecord before it drowned you in a sea of callbacks. If only there was a way to do things “the Rails way” without it falling apart as your application grows. The myth of the infinitely scalable architecture We would like to show you one path to write Rails apps that are a joy to understand and change, even as your team and codebase grows. This book describes a complete toolbox that has served us well for all requirements that we have encountered. Before we do that we need to let you in on an inconvenient secret: Large applications are large. The optimal implementation of a large application will always be more complex than the optimal representation of a smaller app. We cannot make this go away. What we can do is to organize a codebase in a way that “scales logarithmically”. Twice as many models should not mean twice as many problems. A business management consultant would use a chart like this:
Page
6
Introduction 2 Vanilla Rails vs. Structured Rails In order to achieve the green line in the chart above, you do not necessarily need to change the way your application is built. You do not necessarily need to introduce revolutionary architectures to your code. You can probably make it with the tools built into Rails, if you use them in a smarter way. Compare this to sorting algorithms. When a sorting function is too slow, your first thought is very likely not “we should install a Hadoop cluster”. Instead you simply look for an algorithm that scales better and go the Hadoop way when you become Amazon. In a similar fashion this book is not about revolutionary design patterns or magic gems that make all your problems go away. Instead, we will show how to use discipline, consistency and organization to make your application grow more gently. How we structured this book We divided the book into three parts: Part I: New rules for Rails In this part we unlearn bad Rails habits and introduce design conventions for controllers and user- facing models. By being consistent in our design decisions we can make it easier to navigate and understand our application even as its codebase grows. The first part contains the following chapters: • Beautiful controllers • Relearning ActiveRecord • User interactions without a database
Page
7
Introduction 3 Part II: Creating a system for growth As we implement more and more requirements, all that code has to go somewhere. If all we do is add more lines to existing classes and methods, we end up with an unmaintainable mess. In this part we show how to organize code in a way that encourages the creation of new classes which in turn enhances comprehensibility and maintainability. We also lean to contain the side effects that code can have on unrelated parts of our application. The second part discusses the following topics: • Dealing with fat models • A home for interaction-specific code • Extracting service objects • Organizing large codebases with namespaces • Taming stylesheets Part III: Building applications to last We show how to think about future maintenance when making decisions today. We make a case for adopting new technologies and patterns with care, and for taking full responsibility for those techniques and technologies that you do choose to adopt. The last part contains the following chapters: • On following fashions • Surviving the upgrade pace of Rails • Owning your stack • The value of tests
Page
8
New rules for Rails
Page
9
2 Beautiful controllers Let’s talk about controllers. Nobody loves their controllers. When a developer learns about MVC for the first time, she will quickly understand the purpose of models and views. But working with controllers remains awkward: • It is hard to decide whether a new bit of functionality should go into your controller or into your model. Should the model send a notification e-mail or is that the controller’s responsibility? Where to put support code that handles the differences between model and user interface? • Implementing custom mappings between a model and a screen requires too much controller code. Examples for this are actions that operate on multiple models, or a form that has additional fields not contained in the model. It is too cumbersome to support basic interactions like a “form roundtrip”, where an invalid form is displayed again with the offending fields highlighted in red. • Any kind of code put into a controller might as well sit behind a glass wall. You can see it, but it is hard to test and experiment with it. Running controller code requires a complex environment (request, params, sessions, etc.) which Rails must conjure for you. This makes controllers an inaccessible habitat for any kind of code. • Lacking clear guidelines for designing controllers, no two controllers are alike. This makes working on existing UI a chore, since you have to understand how data flows through each individual controller. We cannot make controllers go away. However, by following a few simple guidelines we can reduce the importance of controllers in our application and move controller code to a better place. Because the less business logic is buried inside controllers, the better. The case for consistent controller design Ruby on Rails has few conventions for designing a controller class. There are no rules how to instantiate model classes or how we deal with input errors. The result is a controllers folder where every class works a little differently. This approach does not scale. When every controller follows a different design, a developer needs to learn a new micro API for every UI interaction she needs to change. A better approach is to use a standard controller design for every single user interaction.
Page
10
Beautiful controllers 6 This reduces the mental overhead required to navigate through a large Rails application and understand what is happening. If you knew the layout of a controller class before you even open the file, you could focus on models and views. That is our goal. Having a default design approach also speeds up development of new controllers by removing implementation decisions. You always decide to use CRUD and quickly move on to the parts of your application you really care about: Your models and views. This point becomes more important as your team grows, or once your application becomes too large to fit into your head entirely. Normalizing user interactions How to come up with a default controller design when your application has many different kinds of user interactions? The pattern we use is to reduce every user interaction to a Rails CRUD resource¹. We employ this mapping even if the user interface is not necessarily a typical CRUD interface at first glance. Even interactions that do not look like plain old CRUD resources can be modeled as such. A screen to cancel a subscription can be thought of as destroying a subscription or creating a new cancellation. A screen to upload multiple images at once can be seen as creating an image batch (even if there is no ImageBatch model). By normalizing every user interaction to a CRUD interaction, we can design a beautiful controller layout and reuse it again and again with little changes. A better controller implementation When we take over maintenance for existing Rails projects, we often find unloved controllers, where awkward glue code has been paved over and over again, negotiating between request and model in the most unholy of protocols. It does not have to be that way. We believe that controllers deserve better: • Controllers should receive the same amount of programming discipline as any other type of class. They should be short, DRY² and easy to read. • Controllers should provide the minimum amount of glue code to negotiate between request and model. • Unless there are good reasons against it, controllers should be built against a standard, proven implementation blueprint. ¹http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default ²http://en.wikipedia.org/wiki/Don’t_repeat_yourself
Page
11
Beautiful controllers 7 What is a controller implementation that is so good you want to use it over and over again? Of course Rails has always included a scaffold script that generates controller code. Unfortunately that generated controller is unnecessarily verbose and not DRY at all. Instead we use the following standard implementation for a controller that CRUDs an ActiveRecord (or ActiveModel) class: 1 class NotesController < ApplicationController 2 3 def index 4 load_notes 5 end 6 7 def show 8 load_note 9 end 10 11 def new 12 build_note 13 end 14 15 def create 16 build_note 17 save_note or render 'new' 18 end 19 20 def edit 21 load_note 22 build_note 23 end 24 25 def update 26 load_note 27 build_note 28 save_note or render 'edit' 29 end 30 31 def destroy 32 load_note 33 @note.destroy 34 redirect_to notes_path 35 end 36
Page
12
Beautiful controllers 8 37 private 38 39 def load_notes 40 @notes ||= note_scope.to_a 41 end 42 43 def load_note 44 @note ||= note_scope.find(params[:id]) 45 end 46 47 def build_note 48 @note ||= note_scope.build 49 @note.attributes = note_params 50 end 51 52 def save_note 53 if @note.save 54 redirect_to @note 55 end 56 end 57 58 def note_params 59 note_params = params[:note] 60 note_params ? note_params.permit(:title, :text, :published) : {} 61 end 62 63 def note_scope 64 Note.scoped 65 end 66 67 end Note a couple of things about the code above: • The controller actions are delegating most of their work to helper methods like load_note or build_note. This allows us to not repeat ourselves and is a great way to adapt the behavior of multiple controller actions by changing a single helper method. E.g. if you want to place some restriction on how objects are created, you probably want to apply the same restriction on how objects are updated. It also facilitates the DRY implementation of custom controller actions (like a search action, not visible in the example). • There is a privatemethod note_scopewhich is used by all member actions (show, edit, update, and destroy) to load a Notewith a given ID. It is also used by index to load the list of all notes.
Page
13
Beautiful controllers 9 Note how at no point does an action talk to the Note model directly. By having note_scope guard access to the Notemodel, we have a central place to control which records this controller can show, list or change. This is a great technique to e.g. implement authorization schemes³ where access often depends on the current user. • There is a private method note_params that returns the attributes that can be set through the update and create actions. Note how that method uses strong parameters⁴ to whitelist the attributes that the user is allowed to change. This way we do not accidentally allow changing sensitive attributes, such as foreign keys or admin flags. Strong parameters are available in Rails 4+. If you are on Rails 3 you can use the strong_parameters gem⁵ instead. And if you are on Rails 2 LTS⁶ you can use Hash#slice⁷ to a similar effect. In any case we recommend such an approach in lieu of the attr_accessible pattern that used to be the default in older Rails versions. The reason is that authorization does not belong into the model, and it is really annoying to have attribute whitelisting get in your way when there is not even a remote user to protect from (e.g. the console, scripts, or background jobs). • Every controller action reads or changes a single model. Even if an update involves multiple models, the job of finding and changing the involved records should be pushed to an orchestrating model. You can do so with nested forms⁸ or form models (which we will learn about in a later chapter). By moving glue code from the controller into the model it becomes easier to test and reuse. • Although the controller from the code example maps directly to an ActiveRecord model called Note, this is by no means a requirement. For instance, you might want to use a custom model for forms that are complicated or do not persist to a database. This book will equip you with various techniques for providing a mapping between a user interface and your core domain models. Why have controllers at all? We advocate a very simple and consistent controller design that pushes a lot of code into the model. One might ask: Why have controllers at all? Can’t we conjure some Ruby magic that automatically maps requests onto our model? Well, no. There are still several responsibilities left that controllers should handle: • Security (authentication, authorization) • Parsing and white-listing parameters • Loading or instantiating the model ³Also see our talk: Solving bizarre authorization requirements with Rails. ⁴http://api.rubyonrails.org/classes/ActionController/StrongParameters.html ⁵https://github.com/rails/strong_parameters ⁶https://railslts.com ⁷http://apidock.com/rails/Hash/slice ⁸http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Page
14
Beautiful controllers 10 • Deciding which view to render That code needs to go somewhere and the controller is the right place for it. However, a controller never does the heavy lifting. Controllers should contain the minimum amount of glue to translate between the request, your model and the response. We will learn techniques to extract glue code into classes in “User interactions without a database” and “A home for interaction-specific code”. But before we do that, we need to talk about ActiveRecord. . A note on controller abstractions There are gems like Inherited Resources or Resource Controller that generate a uniform con- troller implementation for you. E.g. the following code would give you a fully implemented UsersController with the seven RESTful default actions with a single line of code: 1 class UsersController < ResourceController::Base 2 end When Ruby loads the UsersController class, Resource Controller would dynamically generate a default implementation for your controller actions. Following the idea of convention over configuration, one would reconfigure the default implemen- tation only if needed: 1 class UsersController < ResourceController::Base 2 3 create.after do 4 Mailer.welcome(@user).deliver 5 end 6 7 end We used to like this idea a lot. However, having used it in several large projects, we now prefer to write out controllers manually again. Here are some reasons why we no longer like to use resource_controller and friends: Configuration can be very awkward
Page
15
Beautiful controllers 11 . Many things that have a natural place in a hand-written controller are awkward to write in a controller abstraction. E.g. using a different model for new/create and edit/update is almost impossible to implement using the configuration options of Resource Controller. Too much magic We rotate on projects a lot. Often new developers on projects using gems such as InheritedResources have a hard time understanding what is happening: Which methods are generated automatically? How do I disable them if not all of them are necessary? Which configuration options do exist? At the end of the day, we saw colleagues spending more time reading documentation than writing code. It’s simply too much magic, too much implicit behavior. Controller abstractions can be useful if you know their pros and cons. We are using them only in very simple CRUD apps with extremely uniform user interfaces. https://github.com/josevalim/inherited_resources https://github.com/makandra/resource_controller http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default https://makandracards.com/makandra/637-default-implementation-of-resource_controller-actions
Page
16
3 Relearning ActiveRecord Developers burnt by large Rails applications often blame their pain on ActiveRecord. We feel that a lof of this criticism is misplaced. ActiveRecord can be a highly effective way to implement user- facing models, meaning models that back an interaction with a human user. An example for a user-facing model is a sign up form that takes a username and password, informs the user if some data is invalid, and only creates a user once when all the information is valid. Since humans are not perfect, a user-facing model needs to revolve around dealing with broken input data. It should make it easy to implement things like the following: • Validation of data entered by a user (e.g. a username must not be taken, a password must have a minimum number of characters) • Form roundtrips: When any input field contains invalid data, the form is displayed again with the invalid fields being highlighted. During a roundtrip all input fields retain their values. Only when everything is valid an action is performed (like creating a record). • Lifecycle callbacks: We want to run code at different points during the human-model- interaction, e.g. do something during the data validation or send an e-mail after successful submission. A form roundtrip after a validation error For this type of model, ActiveRecord can be a great choice. ActiveRecord is focused around error handling and input validation. It allows you to collect and process possibly broken user input with a minimum amount of code in controllers and views.
Page
17
Relearning ActiveRecord 13 Unfortunately, ActiveRecord also comes with plenty of opportunities to shoot yourself in the foot. When you do not model your classes in the way ActiveRecord wants you to, you will find yourself fighting against the library instead of leveraging its power. Understanding the ActiveRecord lifecycle The insidious part about ActiveRecord is that it pretends to get out of your way and let you write a simple Ruby class with methods of your choice. The reality however is that ActiveRecord requires your models to be written in a certain style in order to be effective. Say you have an Invitemodel. Invites are created without an associated User, and can be accepted later. When an invite is accepted, the current user is assigned and a Membership is created. So we provide an accept! method that does all of that: 1 class Invite < ActiveRecord::Base 2 3 belongs_to :user 4 5 def accept!(user) 6 self.user = user 7 self.accepted = true 8 Membership.create!(:user => user) 9 save! 10 end 11 12 end The problem with the code above is that there are a dozen ways to circumvent the accept! method by setting the user or accepted attribute with one of ActiveRecord’s many auto-generated methods. For instance, you cannot prevent other code from simply changing the accepted flag without going through accept!: 1 invite = Invite.find(...) 2 invite.accepted = true 3 invite.save! That is unfortunate, since now we have an Invite record in a strange state: It is accepted, but no user was assigned and the membership record is missing. There are many other ways to accidentally create such an invite, e.g.: • invite.update_attributes!(accepted: true)
Page
18
Relearning ActiveRecord 14 • invite[:accepted] = true; invite.save • Invite.new(accepted: true).save • Invite.create!(accepted: true) In Objects on Rails¹ Avdi Grim called this the “infinite protocol” of ActiveRecord. So what does this mean for our Invite class? We do not want other code to violate data integrity by accidentally calling the wrong method. After all one of the most basic OOP principles is that it should be very hard to misuse a class. Make it hard to misuse your model. One approach we have seen is to get rid of all the “bad” methods that ActiveRecord generates for you², leaving only a whitelist of “good” methods that you can control. But we prefer another way. We love the powerful API that ActiveRecord exposes. We like to be able to use setters, create! or update_attributes! as we see fit. So instead of fighting the nature of ActiveRecord, consider an alternative implementation of the Invite class: 1 class Invite < ActiveRecord::Base 2 3 belongs_to :user 4 5 validates_presence_of :user_id, :if => :accepted? 6 7 after_save :create_membership_on_accept 8 9 private 10 11 def create_membership_on_accept 12 if accepted? && accepted_changed? 13 Membership.create!(:user => user) 14 end 15 end 16 17 end ¹http://objectsonrails.com/ ²https://github.com/objects-on-rails/fig-leaf
Page
19
Relearning ActiveRecord 15 The implementation aboveworks by expressing its API in validations and callbacks. This way clients of the model are free to use any ActiveRecord method to manipulate its state. It can ensure data integrity because ActiveRecord guarantees that callbacks will be called³. Never rely on other code to use the custom model methods that you provide. To enforce an API in ActiveRecord, you must express it in validations and callbacks. Given this statement, you might wonder if there is even a place for model methods that are not callbacks (e.g. the accept! method from a previous code example). And there is! Feel free to pepper your model with convenience methods that facilitate the reading and changing model records. Just do not rely on other code using those methods. Always enforce the integrity of your data with validations and callbacks. . Aren’t callbacks evil? If you have been working with ActiveRecord for a while, you have probably been bitten by models with too many callbacks. If you are now shaking your fist at our suggestion to usemore instead of less callbacks, we ask for your patience. We will discuss and solve this issue in a later chapter (Dealing with Fat Models). The true API of ActiveRecord models Once you start expressing your model’s behavior in validations and callbacks, you realize that the API of your models actually looks like this: • You instantiate a record using any API that suits your needs. • You manipulate the record using any API that suits your needs. • Manipulating a record does not automatically commit changes to the database. Instead the record is put into a “dirty” state. You can inspect dirty records for errors and preview the changes that will be committed. • Once a record passes validations, all changes can be committed to the database in a single transaction. Once you fully embrace the restriction of only using callbacks to express yourself, you can reap many benefits: ³There are a few ActiveRecord methods like update_attribute (singular) that can update a record while skipping callbacks, but they are not used during a regular save call.
Page
20
Relearning ActiveRecord 16 • Your views become significantly simpler by leveraging ActiveRecord’s error tracking. E.g. you no longer need to write and read controller variables to indicate an error state. Invalid form fields are highlighted automatically by the Rails form helpers. • Developers no longer need to understand a customAPI for eachmodel they encounter, making it much easier to understand how a model behaves or how a valid record can be created. • It is no longer possible to accidentally misuse a model and end up with records in an unexpected state. • You can use a standard, lean controller design (see chapter Beautiful controllers). • You will find that there are many useful libraries that work with the standard ActiveRecord API. E.g. the state_machine⁴ gem will prevent invalid state transitions by hooking into ActiveRecord’s validation mechanism. Or the paper_trail⁵ gem can hook into ActiveRecord’s lifecycle events to track changes of your model’s data. Note that this is not exclusive to ActiveRecord models. We will now take a look on how it works for non-persisted classes. ⁴https://github.com/pluginaweek/state_machine ⁵https://github.com/airblade/paper_trail