-
Notifications
You must be signed in to change notification settings - Fork 0
/
rails_models_notes.txt
2581 lines (1753 loc) · 71.1 KB
/
rails_models_notes.txt
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
Rails Models, Migrations, and Associations
==========================================================================================
* More: https://edgeguides.rubyonrails.org/active_record_migrations.html
* https://api.rubyonrails.org/classes/ActiveRecord/Migration.html
* http://guides.rubyonrails.org/migrations.html
* https://github.com/testdouble/good-migrations
* https://medium.com/forest-admin/rails-migrations-tricks-guide-code-cheatsheet-included-dca935354f22
Databases:
============
# mysql
> sudo apt-get install libmysqlclient-dev
# postgres
> sudo apt-get install postgres-client
Models:
=============
Description:
Generates a new model. Pass the model name, either CamelCased or
under_scored, and an optional list of attribute pairs as arguments.
Attribute pairs are field:type arguments specifying the
model's attributes. Timestamps are added by default, so you don't have to
specify them by hand as 'created_at:datetime updated_at:datetime'.
As a special case, specifying 'password:digest' will generate a
password_digest field of string type, and configure your generated model and
tests for use with Active Model has_secure_password (assuming the default ORM
and test framework are being used).
You don't have to think up every attribute up front, but it helps to
sketch out a few so you can start working with the model immediately.
This generator invokes your configured ORM and test framework, which
defaults to Active Record and TestUnit.
Finally, if --parent option is given, it's used as superclass of the
created model. This allows you create Single Table Inheritance models.
If you pass a namespaced model name (e.g. admin/account or Admin::Account)
then the generator will create a module with a table_name_prefix method
to prefix the model's table name with the module name (e.g. admin_accounts)
Available field types:
Just after the field name you can specify a type like text or boolean.
It will generate the column with the associated SQL type. For instance:
`bin/rails generate model post title:string body:text`
will generate a title column with a varchar type and a body column with a text
type. If no type is specified the string type will be used by default.
You can use the following types:
integer
primary_key
decimal
float
boolean
binary
string
text
date
time
datetime
You can also consider `references` as a kind of type. For instance, if you run:
`bin/rails generate model photo title:string album:references`
It will generate an `album_id` column. You should generate these kinds of fields when
you will use a `belongs_to` association, for instance. `references` also supports
polymorphism, you can enable polymorphism like this:
`bin/rails generate model product supplier:references{polymorphic}`
For integer, string, text and binary fields, an integer in curly braces will
be set as the limit:
`bin/rails generate model user pseudo:string{30}`
For decimal, two integers separated by a comma in curly braces will be used
for precision and scale:
`bin/rails generate model product 'price:decimal{10,2}'`
You can add a `:uniq` or `:index` suffix for unique or standard indexes
respectively:
`bin/rails generate model user pseudo:string:uniq`
`bin/rails generate model user pseudo:string:index`
You can combine any single curly brace option with the index options:
`bin/rails generate model user username:string{30}:uniq`
`bin/rails generate model product supplier:references{polymorphic}:index`
If you require a `password_digest` string column for use with
has_secure_password, you can specify `password:digest`:
`bin/rails generate model user password:digest`
If you require a `token` string column for use with
has_secure_token, you can specify `auth_token:token`:
`bin/rails generate model user auth_token:token`
Examples:
---------------
> bin/rails generate model account
For Active Record and TestUnit it creates:
Model: app/models/account.rb
Test: test/models/account_test.rb
Fixtures: test/fixtures/accounts.yml
Migration: db/migrate/XXX_create_accounts.rb
> bin/rails generate model post title:string body:text published:boolean
Creates a Post model with a string title, text body, and published flag.
> bin/rails generate model admin/account
For Active Record and TestUnit it creates:
Module: app/models/admin.rb
Model: app/models/admin/account.rb
Test: test/models/admin/account_test.rb
Fixtures: test/fixtures/admin/accounts.yml
Migration: db/migrate/XXX_create_admin_accounts.rb
Database Preparations & Migrations
===================================
rake db:migrate
rake db:rollback --> one step
rake db:rollback STEP=n
rails generate model Product name:string description:text
$ rails g model wheel car:references
$ rails g model Item name:string description:text product:references
Types:
integer
primary_key
decimal
float
boolean
binary
string
text
date
time
datetime
rails g model Contract user:references name:string social_number:string mobile:string email:string address:text
rails generate model Product name:string description:text
rails generate migration AddPartNumberToProducts
---------------------------------------------------------------------------
Migrations methods:
add_column
add_index
change_column
change_table
create_table
drop_table
remove_column
remove_index
rename_column
Basic format YYYYMMDDHHMMSS_create_products.rb
Supported types
:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:primary_key
:string
:text
:time
:timestamp especial type:
:references
create_table
Commands to create migrations
$ rails generate model Product name:string description:text
$ rails generate migration AddPartNumberToProducts part_number:string
$ rails generate migration RemovePartNumberFromProducts part_number:string
$ rails generate migration AddDetailsToProducts part_number:string price:decimal
change_table
add_column
add_index
add_timestamps
create_table
remove_timestamps
rename_column
rename_index
rename_table
Running Migrations
$ rake db:migrate VERSION=20080906120000
$ rake db:rollback
$ rake db:rollback STEP=3
$ rake db:migrate:redo STEP=3
$ rake db:reset #drop database and recreate it --> this will execute db:seed
$ rake db:migrate:up VERSION=20080906120000
Migrations commands
rake db:migrate # Migrate the database (options: VERSION=x, VERBOSE=false).
rake db:migrate:status # Display status of migrations
rake db:rollback # Rolls the schema back to the previous version (specify steps w/ STEP=n).
rake db:test:prepare # Rebuild it from scratch according to the specs defined in the development database
rails db:prepare # Runs setup if database does not exist, or runs migrations if it does
more Database commands (rake -T db)
rake db:create # Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in t...
rake db:drop # Drops the database for the current Rails.env (use db:drop:all to drop all databases)
rake db:fixtures:load # Load fixtures into the current environment's database.
rake db:schema:dump # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load # Load a schema.rb file into the database
rake db:seed # Load the seed data from db/seeds.rb <------------------
rake db:setup # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)
rake db:structure:dump # Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql
rake db:structure:load # Recreates the databases from the structure.sql file
rake db:sync_templates # Sync theme templates with database
rake db:schema:cache:clear # Clears a db/schema_cache.yml file
rake db:schema:cache:dump # Creates a db/schema_cache.yml file
rake db:version # Retrieves the current schema version number
Reset database
bundle exec rake db:drop RAILS_ENV=test
bundle exec rake db:create RAILS_ENV=test
bundle exec rake db:schema:load RAILS_ENV=test
Or
bundle exec rake db:reset RAILS_ENV=test
drop_table :categories
drop_table :CATEGORY_HIERARCHIES
drop_table :photos
rename_table :tags :categories
* Rails Cheat Sheet: Create Models, Tables and Migrations
------------------------------------------------------------------------
- Create a new table in Rails
bin/rails g model Supplier name:string
bin/rails g model Product name:string:index sku:string{10}:uniq count:integer description:text supplier:references popularity:float 'price:decimal{10,2}' available:boolean availableSince:datetime image:binary
# Resulting migrations:
class CreateSuppliers < ActiveRecord::Migration
def change
create_table :suppliers do |t|
t.string :name
t.timestamps null: false
end
end
end
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.string :sku, limit: 10
t.integer :count
t.text :description
t.references :supplier, index: true, foreign_key: true
t.float :popularity
t.decimal :price, precision: 10, scale: 2
t.boolean :available
t.datetime :availableSince
t.binary :image
t.timestamps null: false
end
add_index :products, :name
add_index :products, :sku, unique: true
end
end
- Rails migration to add a column
bin/rails g migration AddKeywordsSizeToProduct keywords:string size:string
# Resulting migration:
class AddKeywordsSizeToProduct < ActiveRecord::Migration
def change
add_column :products, :keywords, :string
add_column :products, :size, :string
end
end
- Rails migration to remove a column
bin/rails g migration RemoveKeywordsFromProduct keywords
# Resulting migration:
class RemoveKeywordsFromProduct < ActiveRecord::Migration
def change
remove_column :products, :keywords, :string
end
end
- Rails migration to rename a column
bin/rails g migration RenameProductPopularityToRanking
# You need to add the rename_column command manually to the resulting migration:
class RenameProductPopularityToRanking < ActiveRecord::Migration
def change
rename_column :products, :popularity, :ranking
end
end
- Rails migration to change a column type
bin/rails g migration ChangeProductPopularity
# You need to add the change_column command manually to the resulting migration:
class ChangeProductPopularity < ActiveRecord::Migration
def change
change_column :products, :ranking, :decimal, precision: 10, scale: 2
end
end
- Running migrations
# bin/rake db:migrate --> old
> bin/rails db:migrate
In production:
> bin/rails db:migrate RAILS_ENV="production"
- Using a model with view (not table)
class Customer < ActiveRecord::Base
set_table_name 'existing_customers'
Or
self.table_name = "my_customers"
end
- Specifying Primary Key
class Customer < ActiveRecord::Base
set_table_name 'existing_customers'
set_primary_key 'customer_id'
Or
self.primary_key = "customer_id"
end
- Foreign Keys
class Customer < ActiveRecord::Base
set_table_name 'existing_customers'
set_primary_key 'customer_id'
has_many :orders, foreign_key: 'existing_customer_id'
end
class Order < ActiveRecord::Base
belongs_to :customer, foreign_key: 'existing_customer_id'
end
- Option 3: Rebuilding !!! http://tutorials.jumpstartlab.com/topics/models/legacy_databases.html
Seed
======================================================================================================
- basic
rails rails db:seed
rails db:seed:replant # to delete 7 seed data again
- triggered by
rails db:reset and rails db:setup
- setup will create the database first and warn you if ithey are exist ..
- reset will drop and recreat the databases
- create directly
User.create(name: 'Matz')
- seeding from csv
require 'csv'
require_relative './data/users.csv'
def seed_users
csv_file_path = '/[project_path]/db/data/users.csv'
puts 'Seeding users from #{csv_file_path}...'
f = File.new(csv_file_path, 'r')
csv = CSV.new(f)
headers = csv.shift
csv.each do |row|
user_information = {
name: row[0],
age: row[1]
}
inv = User.create(user_information)
end
puts 'Seeding users from #{csv_file_path} done.'
end
- best to execute first specially for testing
Model.destroy_all
- for dates
use helpers such as : 1.week.ago
- check results from acommand
rails runner 'p Movie.pluck :title'
- Using a custom Rails task to seed actual data
rails g task movies seed_genres --> lib/tasks/movies.rake:
namespace :movies do
desc "Seeds genres"
task seed_genres: :environment do
# add then this ..
Genre.create!([{
name: "Action"
},
{
name: "Sci-Fi"
},
{
name: "Adventure"
}])
p "Created #{Genre.count} genres"
end
end
> rails -T movies
> rails movies:seed_genres
- loading seeds from the console
> Rails.application.load_seed
- loops & faker --> (gem 'faker'
Movie.destroy_all
100.times do |index|
Movie.create!(title: Faker::Lorem.sentence(word_count: 3, supplemental: false, random_words_to_add: 0).chop,
director: Faker::Name.name,
storyline: Faker::Lorem.paragraph,
watched_on: Faker::Time.between(from: 4.months.ago, to: 1.week.ago))
end
p "Created #{Movie.count} movies"
- creating a seed file from existing data
lib/tasks/export_data.rake:
namespace :export do
desc "Export users"
task :export_to_seeds => :environment do
User.all.each do |users|
excluded_keys = [‘created_at’, ‘updated_at’, ‘id’]
serialized = country
.serializable_hash
.delete_if{|key,value| excluded_keys.include?(key)}
puts “User.create(#{serialized})”
end
end
end
> rails export:export_to_seed > db/seeds.rb
- creating existing record
user = User.create({....
user.errors.inspect --> #<ActiveModel::Errors [#<ActiveModel::Error attribute=email, type=taken, options={:allow_blank=>true, :if=>:will_save_change_to_email?, :value=>"[email protected]"}>]>
- How to make seeds selective of development or production
db/seeds.rb
case Rails.env
when "development"
...
when "production"
...
end
- Or create
db/seeds/development.rb
db/seeds/production.rb
db/seeds/any_other_environment.rb
db/seeds.rb
load(Rails.root.join( 'db', 'seeds', "#{Rails.env.downcase}.rb"))
Queries (Insert, where, find_by, references, includes, joins, order, limit, pagination ... etc
================================================================================================
New / Create / Select
---------------------
- create
user = User.create(name: "David", occupation: "Code Artist")
user = User.new
user.name = "David"
user.occupation = "Code Artist"
user.save
- you can also
user = User.new do |u|
u.name = "David"
u.occupation = "Code Artist"
end
- find_or_create_by
Customer.find_or_create_by(first_name: 'Andy')
Customer.create_with(locked: false).find_or_create_by(first_name: 'Andy')
Customer.find_or_create_by(first_name: 'Andy') do |c|
c.locked = false
end
Customer.find_or_create_by!(first_name: 'Andy') -> trigger exception if validation failed
- Read
users = User.all
user = User.first
david = User.find_by(name: 'David')
users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)
users = User.where.not(name: 'David', occupation: 'Code Artist').order(created_at: :desc)
- ids
Customer.ids --> SELECT id FROM customers # if self.primary_key = "customer_id" --> SELECT customer_id FROM customers
User.find_by_first_name(fn)
Customer.find_by_first_name_and_orders_count("Ryan", 5)
- find_or_initialize_by
nina = Customer.find_or_initialize_by(first_name: 'Nina')
nina.persisted? # if exists
nina.new_record? # if new record
nina.save
- Finding by SQL
Customer.find_by_sql("SELECT * FROM customers INNER JOIN orders ON customers.id = orders.customer_id ORDER BY customers.created_at desc")
Customer.connection.select_all("SELECT first_name, created_at FROM customers WHERE id = '1'").to_a # ActiveRecord::Result --> .to_a
- pluck
Book.where(out_of_print: true).pluck(:id) --> [1, 2, 3]
Order.distinct.pluck(:status) --> ["shipped", "being_packed", "cancelled"]
Customer.pluck(:id, :first_name) --> [[1, "David"], [2, "Fran"], [3, "Jose"]]
Same
Customer.select(:id).map { |c| c.id }
Customer.select(:id).map(&:id)
Customer.select(:id, :first_name).map { |c| [c.id, c.first_name] }
- method
def name
"I am #{first_name}"
end
Customer.select(:first_name).map &:name
- multiple tables
Order.joins(:customer, :books).pluck("orders.created_at, customers.email, books.title")
Customer.pluck(:first_name).limit(1) # NoMethodError: undefined method `limit' for #<Array:0x007ff34d3ad6d8>
Customer.limit(1).pluck(:first_name) # must be at last
assoc = Customer.includes(:reviews)
assoc.pluck(:id)
- exist
Customer.exists?(1)
Customer.exists?(id: [1,2,3])
Customer.exists?(first_name: ['Jane', 'Sergei'])
Customer.exists? # false if empty
Order.any? --> SELECT 1 FROM orders LIMIT 1
Order.many? --> SELECT COUNT(*) FROM (SELECT 1 FROM orders LIMIT 2)
Order.shipped.any?
Order.shipped.many?
Book.where(out_of_print: true).any?
Book.where(out_of_print: true).many?
Customer.first.orders.any?
Customer.first.orders.many?
- Calculations
Customer.count
Customer.where(first_name: 'Ryan').count
Customer.includes("orders").where(first_name: 'Ryan', orders: { status: 'shipped' }).count
Order.average("subtotal")
Order.minimum("subtotal")
Order.maximum("subtotal")
Order.sum("subtotal")
Customer.where(id: 1).joins(:orders).explain
Customer.where(id: 1).includes(:orders).explain
- Update
user = User.find_by(name: 'David')
user.name = 'Dave'
user.save
user.update(name: 'Dave')
User.update_all "max_login_attempts = 3, must_change_password = 'true'" # no callbacks
User.update(:all, max_login_attempts: 3, must_change_password: true)
- Read only
customer = Customer.readonly.first
customer.visits += 1
customer.save
- Locking Records for Update (Optimistic Locking, Pessimistic Locking)
- In order to use optimistic locking, the table needs to have a column called lock_version of type integer.
- An ActiveRecord::StaleObjectError exception is thrown if that has occurred and the update is ignored.
- OPtimistic
c1 = Customer.find(1)
c2 = Customer.find(1)
c1.first_name = "Sandra"
c1.save
c2.first_name = "Michael"
c2.save # Raises an ActiveRecord::StaleObjectError
- Pessimistic Locking
Book.transaction do
book = Book.lock.first
book.title = 'Algorithms, second edition'
book.save!
end
Book.transaction do
book = Book.lock("LOCK IN SHARE MODE").find(1)
book.increment!(:views)
end
book = Book.first
book.with_lock do
# This block is called within a transaction,
# book is already locked.
book.increment!(:views)
end
- Delete
user.destroy
User.destroy_by(name: 'David')
User.destroy_all
Querying
------------------------------------------------------------------------
annotate
find
create_with
distinct
eager_load
extending
extract_associated
from
group
having
includes
joins
left_outer_joins
limit
lock
none
offset
optimizer_hints
order
preload
readonly
references
reorder
reselect
reverse_order
select
where
customer = Customer.find(10)
customers = Customer.find([1, 10])
customer = Customer.take --> SELECT * FROM customers LIMIT 1
customers = Customer.take(2) --> SELECT * FROM customers LIMIT 2
customer = Customer.first
customers = Customer.first(3) --> SELECT * FROM customers ORDER BY customers.id ASC LIMIT 3
customer = Customer.order(:first_name).first
customer = Customer.last
customers = Customer.last(3)
customer = Customer.order(:first_name).last
Customer.find_by first_name: 'Lifo'
Customer.where(first_name: 'Lifo').take
Customer.find_by! first_name: 'does not exist' --> ActiveRecord::RecordNotFound
Customer.where(first_name: 'does not exist').take!
# entire table
Customer.all.each do |customer|
NewsMailer.weekly(customer).deliver_now
end
# find_each retrieves customers in batches of 1000 and yields them to the block one by one: - repeat next 1000
Customer.find_each do |customer|
NewsMailer.weekly(customer).deliver_now
end
Customer.where(weekly_subscriber: true).find_each(batch_size: 5000) do |customer|
NewsMailer.weekly(customer).deliver_now
end
# also use -->
start: 2000
start: 2000, finish: 10000
- you can yield batches
Customer.find_in_batches do |customers|
export.add_customers(customers)
end
- Conditions
Book.where("title = ?", params[:title])
Book.where("title = ? AND out_of_print = ?", params[:title], false)
Book.where("created_at >= :start_date AND created_at <= :end_date", {start_date: params[:start_date], end_date: params[:end_date]})
Book.where('out_of_print' => true)
Book.where(author: author) # association
Author.joins(:books).where(books: { author: author })
Book.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
Customer.where(orders_count: [1,3,5])
Customer.where.not(orders_count: [1,3,5])
Customer.where(last_name: 'Smith').or(Customer.where(orders_count: [1,3,5])) # OR
Customer.where(last_name: 'Smith').where(orders_count: [1,3,5])) # AND
Customer.where(id: [1, 2]).and(Customer.where(id: [2, 3]))
- Ordering
Book.order(title: :asc, created_at: :desc)
Book.order("title ASC, created_at DESC")
- Select
Book.select(:isbn, :out_of_print)
Book.select("isbn, out_of_print")
Customer.select(:last_name).distinct
- Limit, Offset
Customer.limit(5).offset(30)
- group
Order.select("created_at").group("created_at")
Order.group(:status).count
- Having
Order.select("created_at, sum(total) as total_price").group("created_at").having("sum(total) > ?", 200)
- Overriding Conditions
Book.where('id > 100').limit(20).order('id desc').unscope(:order) # remove order by ..
Book.where(id: 10, out_of_print: false).unscope(where: :id)
# SELECT books.* FROM books WHERE out_of_print = 0
Book.order('id desc').merge(Book.unscope(:order))
Book.where('id > 10').limit(20).order('id desc').only(:order, :where) # remove limit
- reselect
Book.select(:title, :isbn).reselect(:created_at) # only created_at
Book.select(:title, :isbn).select(:created_at) # with created_at
- reorder, reverse_order
has_many :books, -> { order(year_published: :desc) }
Author.find(10).books.reorder('year_published ASC')
Book.where("author_id > 10").order(:year_published).reverse_order
- rewhere
Book.where(out_of_print: true).rewhere(out_of_print: false) # new where
Book.where(out_of_print: true).where(out_of_print: false) # with
- Null relation
if reviews.count > 5
reviews
else
Review.none # Does not meet minimum threshold yet
end
# https://guides.rubyonrails.org/active_record_querying.html
- Includes, references and joins
--------------------------------------------------
- Join
Post.joins(:comments).where(:comments => {author: 'Derek'}).map { |post| post.title }
# SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE "comments"."author" = $1
- Do joins prevent N+1 queries? NO
This will run query for each comment fetched
Post.joins(:comments).where(:comments => {author: 'Derek'}).map { |post| post.comments.size }
# SELECT "posts".* FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE "comments"."author" = $1
# SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = $1
# ...
Author.joins(books: [{reviews: { customer: :orders} }, :supplier] )
SELECT * FROM authors
INNER JOIN books ON books.author_id = authors.id
INNER JOIN reviews ON reviews.book_id = books.id
INNER JOIN customers ON customers.id = reviews.customer_id
INNER JOIN orders ON orders.customer_id = customers.id
INNER JOIN suppliers ON suppliers.id = books.supplier_id
time_range = (Time.now.midnight - 1.day)..Time.now.midnight
Customer.joins(:orders).where('orders.created_at' => time_range).distinct
Customer.joins(:orders).merge(Order.created_in_time_range(time_range)).distinct
Customer.left_outer_joins(:reviews).distinct.select('customers.*, COUNT(reviews.*) AS reviews_count').group('customers.id')
- Can joins be combined with includes, preload, and eager_load? Yes
- Can includes prevent N+1 queries? yes
- From multiple tables
Customer
.select('customers.id, customers.last_name, reviews.body')
.joins(:reviews)
.where('reviews.created_at > ?', 1.week.ago)
- Includes
- Solution to N + 1 queries problem
includes
preload
eager_load
Post.includes(:comments).map { |post| post.comments.size }
# SELECT "comments".* FROM "comments" WHERE "comments"."post_id" IN (1, 3, 4, 5, 6)
- Does includes always generate a separate query to fetch the records in the relationship? No
includes will either use a separate query (like above) or a LEFT OUTER JOIN.
If you have a where or order clause that references a relationship, a LEFT OUTER JOIN is used versus a separate query.
- nested
Customer.includes(orders: {books: [:supplier, :author]}).find(1)
Author.includes(:books).where(books: { out_of_print: true }) # LEFT OUTER JOIN
Post.includes(:comments).references(:comments).map { |post| post.comments.size }
- What happens when I apply conditions to a relationship referenced via includes?
ActiveRecord will return all of the parent records and just the relationship records that match the condition.
Post.includes(:comments).references(:comments).where(comments => {author: 'Derek'}).map { |post| post.comments.size }
- Does includes prevent all N+1 queries? No
If you are accessing data in a nested relationship, that data isn't preloaded.
For example, an additional query would be required to load the Comment#likes association for each comment:
<% post.comments.each do |comment| %>
<%= comment.likes.map { |like| like.user_avatar_url }
<% end %>
- Can I prevent N+1s in nested relationships? Yes. You can load nested relationships via includes:
Post.includes(comments => :likes).references(:comments).map { |post| post.comments.size }
- Should I always always load data from nested relationships?
No. It's very easy to end up initializing a significant number of records.
For example, a popular Comment may have thousands of Like records, which would result in a slow query and significant memory allocations.