OSDN Git Service

Regular updates
[twpd/master.git] / arel.md
1 ---
2 title: Arel
3 category: Rails
4 ---
5
6 ### Tables
7
8 ```rb
9 users = Arel::Table.new(:users)
10 users = User.arel_table  # ActiveRecord model
11 ```
12
13 ### Fields
14
15 ```rb
16 users[:name]
17 users[:id]
18 ```
19
20 ### `where` (restriction)
21
22 ```rb
23 users.where(users[:name].eq('amy'))
24 # SELECT * FROM users WHERE users.name = 'amy'
25 ```
26
27 ### `select` (projection)
28
29 ```rb
30 users.project(users[:id])
31 # SELECT users.id FROM users
32 ```
33
34 ### `join`
35 #### basic join
36 In ActiveRecord (without Arel), if `:photos` is the name of the association, use `joins`
37 ```rb
38 users.joins(:photos)
39 ```
40
41 In Arel, if `photos` is defined as the Arel table,
42 ```rb
43 photos = Photo.arel_table
44 users.join(photos) 
45 users.join(photos, Arel::Nodes::OuterJoin).on(users[:id].eq(photos[:user_id]))
46 ```
47
48 #### join with conditions
49 ```rb
50 users.joins(:photos).merge(Photo.where(published: true))
51 ```
52
53 If the simpler version doesn't help and you want to add more SQL statements to it:
54 ```rb
55 users.join(
56    users.join(photos, Arel::Nodes::OuterJoin)
57    .on(photos[:user_id].eq(users[:id]).and(photos[:published].eq(true)))
58 )
59 ```
60
61 #### advanced join
62 multiple `joins` with the same table but different meanings and/or conditions
63 ```rb
64 creators = User.arel_table.alias('creators')
65 updaters = User.arel_table.alias('updaters')
66 photos = Photo.arel_table
67
68 photos_with_credits = photos
69 .join(photos.join(creators, Arel::Nodes::OuterJoin).on(photos[:created_by_id].eq(creators[:id])))
70 .join(photos.join(updaters, Arel::Nodes::OuterJoin).on(photos[:assigned_id].eq(updaters[:id])))
71 .project(photos[:name], photos[:created_at], creators[:name].as('creator'), updaters[:name].as('editor'))
72
73 photos_with_credits.to_sql
74 # => "SELECT `photos`.`name`, `photos`.`created_at`, `creators`.`name` AS creator, `updaters`.`name` AS editor FROM `photos` INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `creators` ON `photos`.`created_by_id` = `creators`.`id`) INNER JOIN (SELECT FROM `photos` LEFT OUTER JOIN `users` `updaters` ON `photos`.`updated_by_id` = `updaters`.`id`)"
75
76 # after the request is done, you can use the attributes you named
77 # it's as if every Photo record you got has "creator" and "editor" fields, containing creator name and editor name
78 photos_with_credits.map{|x|
79   "#{photo.name} - copyright #{photo.created_at.year} #{photo.creator}, edited by #{photo.editor}"
80 }.join('; ')
81 ```
82
83 ### `limit` / `offset`
84
85 ```rb
86 users.take(5) # => SELECT * FROM users LIMIT 5
87 users.skip(4) # => SELECT * FROM users OFFSET 4
88 ```
89
90 ### Aggregates
91
92 ```rb
93 users.project(users[:age].sum) # .average .minimum .maximum
94 users.project(users[:id].count)
95 users.project(users[:id].count.as('user_count'))
96 ```
97
98 ### `order`
99
100 ```rb
101 users.order(users[:name])
102 users.order(users[:name], users[:age].desc)
103 users.reorder(users[:age])
104 ```
105
106 ### With ActiveRecord
107
108 ```rb
109 User.arel_table
110 User.where(id: 1).arel
111 ```
112
113 ### Clean code with arel
114
115 Most of the clever stuff should be in scopes, e.g. the code above could become:
116 ```rb
117 photos_with_credits = Photo.with_creator.with_editor
118 ```
119
120 You can store requests in variables then add SQL segments:
121 ```rb
122 all_time      = photos_with_credits.count
123 this_month    = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month))
124 recent_photos = photos_with_credits.where(photos[:created_at].gteq(Date.today.beginning_of_month)).limit(5)
125 ```
126
127 ## Reference
128
129 * <http://github.com/rails/arel>