-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
README.adoc
1823 lines (1328 loc) · 47 KB
/
README.adoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
= The Rails Style Guide
:idprefix:
:idseparator: -
:sectanchors:
:sectlinks:
:toc: preamble
:toclevels: 1
ifndef::backend-pdf[]
:toc-title: pass:[<h2>Table of Contents</h2>]
endif::[]
:source-highlighter: rouge
== Introduction
By https://github.com/bbatsov[Bozhidar Batsov]
[quote]
____
Role models are important.
-- Officer Alex J. Murphy / RoboCop
____
ifdef::env-github[]
TIP: You can find a beautiful version of this guide with much improved navigation at https://rails.rubystyle.guide.
endif::[]
The goal of this guide is to present a set of best practices and style prescriptions for Ruby on Rails development.
It's a complementary guide to the already existing community-driven https://github.com/rubocop/ruby-style-guide[Ruby coding style guide].
This Rails style guide recommends best practices so that real-world Rails programmers can write code that can be maintained by other real-world Rails programmers.
A style guide that reflects real-world usage gets used, and a style guide that holds to an ideal that has been rejected by the people it is supposed to help risks not getting used at all - no matter how good it is.
The guide is separated into several sections of related rules.
I've tried to add the rationale behind the rules (if it's omitted I've assumed it's pretty obvious).
I didn't come up with all the rules out of nowhere - they are mostly based on my extensive career as a professional software engineer, feedback and suggestions from members of the Rails community and various highly regarded Rails programming resources.
NOTE: Some of the advice here is applicable only to recent versions of Rails.
You can generate a PDF copy of this guide using https://asciidoctor.org/docs/asciidoctor-pdf/[AsciiDoctor PDF], and an HTML copy https://asciidoctor.org/docs/convert-documents/#converting-a-document-to-html[with] https://asciidoctor.org/#installation[AsciiDoctor] using the following commands:
[source,shell]
----
# Generates README.pdf
asciidoctor-pdf -a allow-uri-read README.adoc
# Generates README.html
asciidoctor README.adoc
----
[TIP]
====
Install the `rouge` gem to get nice syntax highlighting in the generated document.
[source,shell]
----
gem install rouge
----
====
Translations of the guide are available in the following languages:
* https://github.com/satour/rails-style-guide/blob/master/README-jaJA.md[Japanese]
* https://github.com/arbox/rails-style-guide/blob/master/README-ruRU.md[Russian]
TIP: https://github.com/rubocop/rubocop[RuboCop], a static code analyzer (linter) and formatter, has a https://github.com/rubocop/rubocop-rails[`rubocop-rails`] extension, based on this style guide.
== Configuration
=== Config Initializers [[config-initializers]]
Put custom initialization code in `config/initializers`.
The code in initializers executes on application startup.
=== Gem Initializers [[gem-initializers]]
Keep initialization code for each gem in a separate file with the same name as the gem, for example `carrierwave.rb`, `active_admin.rb`, etc.
=== Dev/Test/Prod Configs [[dev-test-prod-configs]]
Adjust accordingly the settings for development, test and production environment (in the corresponding files under `config/environments/`)
Mark additional assets for precompilation (if any):
[source,ruby]
----
# config/environments/production.rb
# Precompile additional assets (application.js, application.css,
#and all non-JS/CSS are already added)
config.assets.precompile += %w( rails_admin/rails_admin.css rails_admin/rails_admin.js )
----
=== App Config [[app-config]]
Keep configuration that's applicable to all environments in the `config/application.rb` file.
=== Load Rails Config Defaults [[config-defaults]]
When upgrading to a newer Rails version, your application's configuration setting will remain on the previous version. To take advantage of the latest recommended Rails practices, the `config.load_defaults` setting should match your Rails version.
[source,ruby]
----
# good
config.load_defaults 6.1
----
=== Staging Like Prod [[staging-like-prod]]
Avoid creating additional environment configurations than the defaults of `development`, `test` and `production`.
If you need a production-like environment such as staging, use environment variables for configuration options.
=== YAML Config [[yaml-config]]
Keep any additional configuration in YAML files under the `config/` directory.
Since Rails 4.2 YAML configuration files can be easily loaded with the new `config_for` method:
[source,ruby]
----
Rails::Application.config_for(:yaml_file)
----
== Routing
=== Member Collection Routes [[member-collection-routes]]
When you need to add more actions to a RESTful resource (do you really need them at all?) use `member` and `collection` routes.
[source,ruby]
----
# bad
get 'subscriptions/:id/unsubscribe'
resources :subscriptions
# good
resources :subscriptions do
get 'unsubscribe', on: :member
end
# bad
get 'photos/search'
resources :photos
# good
resources :photos do
get 'search', on: :collection
end
----
=== Many Member Collection Routes [[many-member-collection-routes]]
If you need to define multiple `member/collection` routes use the alternative block syntax.
[source,ruby]
----
resources :subscriptions do
member do
get 'unsubscribe'
# more routes
end
end
resources :photos do
collection do
get 'search'
# more routes
end
end
----
=== Nested Routes [[nested-routes]]
Use nested routes to express better the relationship between Active Record models.
[source,ruby]
----
class Post < ApplicationRecord
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
end
# routes.rb
resources :posts do
resources :comments
end
----
=== Shallow Routes [[shallow-routes]]
If you need to nest routes more than 1 level deep then use the `shallow: true` option.
This will save user from long URLs `posts/1/comments/5/versions/7/edit` and you from long URL helpers `edit_post_comment_version`.
[source,ruby]
----
resources :posts, shallow: true do
resources :comments do
resources :versions
end
end
----
=== Namespaced Routes [[namespaced-routes]]
Use namespaced routes to group related actions.
[source,ruby]
----
namespace :admin do
# Directs /admin/products/* to Admin::ProductsController
# (app/controllers/admin/products_controller.rb)
resources :products
end
----
=== No Wild Routes [[no-wild-routes]]
Never use the legacy wild controller route.
This route will make all actions in every controller accessible via GET requests.
[source,ruby]
----
# very bad
match ':controller(/:action(/:id(.:format)))'
----
=== No Match Routes [[no-match-routes]]
Don't use `match` to define any routes unless there is need to map multiple request types among `[:get, :post, :patch, :put, :delete]` to a single action using `:via` option.
== Controllers
=== Skinny Controllers [[skinny-controllers]]
Keep the controllers skinny - they should only retrieve data for the view layer and shouldn't contain any business logic (all the business logic should naturally reside in the model).
=== One Method [[one-method]]
Each controller action should (ideally) invoke only one method other than an initial find or new.
=== Shared Instance Variables [[shared-instance-variables]]
Minimize the number of instance variables passed between a controller and a view.
=== Lexically Scoped Action Filter [[lexically-scoped-action-filter]]
Controller actions specified in the option of Action Filter should be in lexical scope.
The ActionFilter specified for an inherited action makes it difficult to understand the scope of its impact on that action.
[source,ruby]
----
# bad
class UsersController < ApplicationController
before_action :require_login, only: :export
end
# good
class UsersController < ApplicationController
before_action :require_login, only: :export
def export
end
end
----
== Controllers: Rendering [[rendering]]
=== Inline Rendering [[inline-rendering]]
Prefer using a template over inline rendering.
[source,ruby]
----
# very bad
class ProductsController < ApplicationController
def index
render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>", type: :erb
end
end
# good
## app/views/products/index.html.erb
<%= render partial: 'product', collection: products %>
## app/views/products/_product.html.erb
<p><%= product.name %></p>
<p><%= product.price %></p>
## app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
render :index
end
end
----
=== Plain Text Rendering [[plain-text-rendering]]
Prefer `render plain:` over `render text:`.
[source,ruby]
----
# bad - sets MIME type to `text/html`
...
render text: 'Ruby!'
...
# bad - requires explicit MIME type declaration
...
render text: 'Ruby!', content_type: 'text/plain'
...
# good - short and precise
...
render plain: 'Ruby!'
...
----
=== HTTP Status Code Symbols [[http-status-code-symbols]]
Prefer https://gist.github.com/mlanett/a31c340b132ddefa9cca[corresponding symbols] to numeric HTTP status codes.
They are meaningful and do not look like "magic" numbers for less known HTTP status codes.
[source,ruby]
----
# bad
...
render status: 403
...
# good
...
render status: :forbidden
...
----
== Models
=== Model Classes [[model-classes]]
Introduce non-Active Record model classes freely.
=== Meaningful Model Names [[meaningful-model-names]]
Name the models with meaningful (but short) names without abbreviations.
=== Non-ActiveRecord Models [[non-activerecord-models]]
If you need objects that support ActiveRecord-like behavior (like validations) without the database functionality, use `ActiveModel::Model`.
[source,ruby]
----
class Message
include ActiveModel::Model
attr_accessor :name, :email, :content, :priority
validates :name, presence: true
validates :email, format: { with: /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i }
validates :content, length: { maximum: 500 }
end
----
Starting with Rails 6.1, you can also extend the attributes API from ActiveRecord using `ActiveModel::Attributes`.
[source,ruby]
----
class Message
include ActiveModel::Model
include ActiveModel::Attributes
attribute :name, :string
attribute :email, :string
attribute :content, :string
attribute :priority, :integer
validates :name, presence: true
validates :email, format: { with: /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i }
validates :content, length: { maximum: 500 }
end
----
=== Model Business Logic [[model-business-logic]]
Unless they have some meaning in the business domain, don't put methods in your model that just format your data (like code generating HTML).
These methods are most likely going to be called from the view layer only, so their place is in helpers.
Keep your models for business logic and data-persistence only.
== Models: Active Record [[activerecord]]
=== Keep Active Record Defaults [[keep-ar-defaults]]
Avoid altering Active Record defaults (table names, primary key, etc) unless you have a very good reason (like a database that's not under your control).
[source,ruby]
----
# bad - don't do this if you can modify the schema
class Transaction < ApplicationRecord
self.table_name = 'order'
...
end
----
=== Enums [[enums]]
Prefer using the hash syntax for `enum`. Array makes the database values implicit
& any insertion/removal/rearrangement of values in the middle will most probably
lead to broken code.
[source,ruby]
----
class Transaction < ApplicationRecord
# bad - implicit values - ordering matters
enum type: %i[credit debit]
# good - explicit values - ordering does not matter
enum type: {
credit: 0,
debit: 1
}
end
----
=== Macro Style Methods [[macro-style-methods]]
Group macro-style methods (`has_many`, `validates`, etc) in the beginning of the class definition.
[source,ruby]
----
class User < ApplicationRecord
# keep the default scope first (if any)
default_scope { where(active: true) }
# constants come up next
COLORS = %w(red green blue)
# afterwards we put attr related macros
attr_accessor :formatted_date_of_birth
attr_accessible :login, :first_name, :last_name, :email, :password
# Rails 4+ enums after attr macros
enum role: { user: 0, moderator: 1, admin: 2 }
# followed by association macros
belongs_to :country
has_many :authentications, dependent: :destroy
# and validation macros
validates :email, presence: true
validates :username, presence: true
validates :username, uniqueness: { case_sensitive: false }
validates :username, format: { with: /\A[A-Za-z][A-Za-z0-9._-]{2,19}\z/ }
validates :password, format: { with: /\A\S{8,128}\z/, allow_nil: true }
# next we have callbacks
before_save :cook
before_save :update_username_lower
# other macros (like devise's) should be placed after the callbacks
...
end
----
=== `has_many :through` [[has-many-through]]
Prefer `has_many :through` to `has_and_belongs_to_many`.
Using `has_many :through` allows additional attributes and validations on the join model.
[source,ruby]
----
# not so good - using has_and_belongs_to_many
class User < ApplicationRecord
has_and_belongs_to_many :groups
end
class Group < ApplicationRecord
has_and_belongs_to_many :users
end
# preferred way - using has_many :through
class User < ApplicationRecord
has_many :memberships
has_many :groups, through: :memberships
end
class Membership < ApplicationRecord
belongs_to :user
belongs_to :group
end
class Group < ApplicationRecord
has_many :memberships
has_many :users, through: :memberships
end
----
=== Read Attribute [[read-attribute]]
Prefer `self[:attribute]` over `read_attribute(:attribute)`.
[source,ruby]
----
# bad
def amount
read_attribute(:amount) * 100
end
# good
def amount
self[:amount] * 100
end
----
=== Write Attribute [[write-attribute]]
Prefer `self[:attribute] = value` over `write_attribute(:attribute, value)`.
[source,ruby]
----
# bad
def amount
write_attribute(:amount, 100)
end
# good
def amount
self[:amount] = 100
end
----
=== New-style Validations [[new-style-validations]]
Always use the http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/["new-style" validations].
[source,ruby]
----
# bad
validates_presence_of :email
validates_length_of :email, maximum: 100
# good
validates :email, presence: true, length: { maximum: 100 }
----
=== Custom Validation Methods
When naming custom validation methods, adhere to the simple rules:
- `validate :method_name` reads like a natural statement
- the method name explains what it checks
- the method is recognizable as a validation method by its name, not a predicate method
[source,ruby]
----
# good
validate :expiration_date_cannot_be_in_the_past
validate :discount_cannot_be_greater_than_total_value
validate :ensure_same_topic_is_chosen
# also good - explicit prefix
validate :validate_birthday_in_past
validate :validate_sufficient_quantity
validate :must_have_owner_with_no_other_items
validate :must_have_shipping_units
# bad
validate :birthday_in_past
validate :owner_has_no_other_items
----
=== Single-attribute Validations [[single-attribute-validations]]
To make validations easy to read, don't list multiple attributes per validation.
[source,ruby]
----
# bad
validates :email, :password, presence: true
validates :email, length: { maximum: 100 }
# good
validates :email, presence: true, length: { maximum: 100 }
validates :password, presence: true
----
=== Custom Validator File [[custom-validator-file]]
When a custom validation is used more than once or the validation is some regular expression mapping, create a custom validator file.
[source,ruby]
----
# bad
class Person
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }
end
# good
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'is not a valid email') unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
end
class Person
validates :email, email: true
end
----
=== App Validators [[app-validators]]
Keep custom validators under `app/validators`.
=== Custom Validators Gem [[custom-validators-gem]]
Consider extracting custom validators to a shared gem if you're maintaining several related apps or the validators are generic enough.
=== Named Scopes [[named-scopes]]
Use named scopes freely.
[source,ruby]
----
class User < ApplicationRecord
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
scope :with_orders, -> { joins(:orders).select('distinct(users.id)') }
end
----
=== Named Scope Class [[named-scope-class]]
When a named scope defined with a lambda and parameters becomes too complicated, it is preferable to make a class method instead which serves the same purpose of the named scope and returns an `ActiveRecord::Relation` object.
Arguably you can define even simpler scopes like this.
[source,ruby]
----
class User < ApplicationRecord
def self.with_orders
joins(:orders).select('distinct(users.id)')
end
end
----
=== Callbacks Order [[callbacks-order]]
Order callback declarations in the order in which they will be executed.
For reference, see https://guides.rubyonrails.org/active_record_callbacks.html#available-callbacks[Available Callbacks].
[source,ruby]
----
# bad
class Person
after_commit :after_commit_callback
before_validation :before_validation_callback
end
# good
class Person
before_validation :before_validation_callback
after_commit :after_commit_callback
end
----
=== Beware Skip Model Validations [[beware-skip-model-validations]]
Beware of the behavior of the https://guides.rubyonrails.org/active_record_validations.html#skipping-validations[following] methods.
They do not run the model validations and could easily corrupt the model state.
[source,ruby]
----
# bad
Article.first.decrement!(:view_count)
DiscussionBoard.decrement_counter(:post_count, 5)
Article.first.increment!(:view_count)
DiscussionBoard.increment_counter(:post_count, 5)
person.toggle :active
product.touch
Billing.update_all("category = 'authorized', author = 'David'")
user.update_attribute(:website, 'example.com')
user.update_columns(last_request_at: Time.current)
Post.update_counters 5, comment_count: -1, action_count: 1
# good
user.update_attributes(website: 'example.com')
----
=== User-friendly URLs [[user-friendly-urls]]
Use user-friendly URLs.
Show some descriptive attribute of the model in the URL rather than its `id`.
There is more than one way to achieve this.
==== Override the `to_param` Method of the Model
This method is used by Rails for constructing a URL to the object.
The default implementation returns the `id` of the record as a String.
It could be overridden to include another human-readable attribute.
[source,ruby]
----
class Person
def to_param
"#{id} #{name}".parameterize
end
end
----
In order to convert this to a URL-friendly value, `parameterize` should be called on the string.
The `id` of the object needs to be at the beginning so that it can be found by the `find` method of Active Record.
==== `friendly_id` Gem
It allows creation of human-readable URLs by using some descriptive attribute of the model instead of its `id`.
[source,ruby]
----
class Person
extend FriendlyId
friendly_id :name, use: :slugged
end
----
Check the https://github.com/norman/friendly_id[gem documentation] for more information about its usage.
=== `find_each` [[find-each]]
Use `find_each` to iterate over a collection of AR objects.
Looping through a collection of records from the database (using the `all` method, for example) is very inefficient since it will try to instantiate all the objects at once.
In that case, batch processing methods allow you to work with the records in batches, thereby greatly reducing memory consumption.
[source,ruby]
----
# bad
Person.all.each do |person|
person.do_awesome_stuff
end
Person.where('age > 21').each do |person|
person.party_all_night!
end
# good
Person.find_each do |person|
person.do_awesome_stuff
end
Person.where('age > 21').find_each do |person|
person.party_all_night!
end
----
=== `before_destroy` [[before_destroy]]
Since https://github.com/rails/rails/issues/3458[Rails creates callbacks for dependent associations], always call `before_destroy` callbacks that perform validation with `prepend: true`.
[source,ruby]
----
# bad (roles will be deleted automatically even if super_admin? is true)
has_many :roles, dependent: :destroy
before_destroy :ensure_deletable
def ensure_deletable
raise "Cannot delete super admin." if super_admin?
end
# good
has_many :roles, dependent: :destroy
before_destroy :ensure_deletable, prepend: true
def ensure_deletable
raise "Cannot delete super admin." if super_admin?
end
----
=== `has_many`/`has_one` Dependent Option [[has_many-has_one-dependent-option]]
Define the `dependent` option to the `has_many` and `has_one` associations.
[source,ruby]
----
# bad
class Post < ApplicationRecord
has_many :comments
end
# good
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
end
----
=== `save!` [[save-bang]]
When persisting AR objects always use the exception raising bang! method or handle the method return value.
This applies to `create`, `save`, `update`, `destroy`, `first_or_create` and `find_or_create_by`.
[source,ruby]
----
# bad
user.create(name: 'Bruce')
# bad
user.save
# good
user.create!(name: 'Bruce')
# or
bruce = user.create(name: 'Bruce')
if bruce.persisted?
...
else
...
end
# good
user.save!
# or
if user.save
...
else
...
end
----
== Models: Active Record Queries [[activerecord-queries]]
=== Avoid Interpolation [[avoid-interpolation]]
Avoid string interpolation in queries, as it will make your code susceptible to SQL injection attacks.
[source,ruby]
----
# bad - param will be interpolated unescaped
Client.where("orders_count = #{params[:orders]}")
# good - param will be properly escaped
Client.where('orders_count = ?', params[:orders])
----
=== Named Placeholder [[named-placeholder]]
Consider using named placeholders instead of positional placeholders when you have more than 1 placeholder in your query.
[source,ruby]
----
# okish
Client.where(
'orders_count >= ? AND country_code = ?',
params[:min_orders_count], params[:country_code]
)
# good
Client.where(
'orders_count >= :min_orders_count AND country_code = :country_code',
min_orders_count: params[:min_orders_count], country_code: params[:country_code]
)
----
=== `find` [[find]]
Prefer `find` over `where.take!`, `find_by!`, and `find_by_id!` when you need to retrieve a single record by primary key id and raise `ActiveRecord::RecordNotFound` when the record is not found.
[source,ruby]
----
# bad
User.where(id: id).take!
# bad
User.find_by_id!(id)
# bad
User.find_by!(id: id)
# good
User.find(id)
----
=== `find_by` [[find_by]]
Prefer `find_by` over `where.take` and `find_by_attribute` when you need to retrieve a single record by one or more attributes and return `nil` when the record is not found.
[source,ruby]
----
# bad
User.where(email: email).take
User.where(first_name: 'Bruce', last_name: 'Wayne').take
# bad
User.find_by_email(email)
User.find_by_first_name_and_last_name('Bruce', 'Wayne')
# good
User.find_by(email: email)
User.find_by(first_name: 'Bruce', last_name: 'Wayne')
----
=== Hash conditions [[where-not]] [[hash-conditions]]
Prefer passing conditions to `where` and `where.not` as a hash over using fragments of SQL.
[source,ruby]
----
# bad
User.where("name = ?", name)
# good
User.where(name: name)
# bad
User.where("id != ?", id)
# good
User.where.not(id: id)
----
=== Order by `id` [[order-by-id]]
Don't use the `id` column for ordering.
The sequence of ids is not guaranteed to be in any particular order, despite often (incidentally) being chronological.
Use a timestamp column to order chronologically.
As a bonus the intent is clearer.
[source,ruby]
----
# bad
scope :chronological, -> { order(id: :asc) }
# good
scope :chronological, -> { order(created_at: :asc) }
----
=== `pluck`
Use https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck[pluck] to select a single value from multiple records.
[source,ruby]
----
# bad
User.all.map(&:name)
# bad
User.all.map { |user| user[:name] }
# good
User.pluck(:name)
----
=== `pick`
Use https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pick[pick] to select a single value from a single record.
[source,ruby]
----
# bad
User.pluck(:name).first
# bad
User.first.name
# good
User.pick(:name)
----
=== `ids` [[ids]]
Prefer `ids` over `pluck(:id)`.
[source,ruby]
----
# bad
User.pluck(:id)
# good
User.ids
----
=== Squished Heredocs [[squished-heredocs]]
When specifying an explicit query in a method such as `find_by_sql`, use heredocs with `squish`.
This allows you to legibly format the SQL with line breaks and indentations, while supporting syntax highlighting in many tools (including GitHub, Atom, and RubyMine).
[source,ruby]
----
User.find_by_sql(<<-SQL.squish)
SELECT
users.id, accounts.plan
FROM
users
INNER JOIN
accounts
ON