Here are some common problems and solutions for ActiveRecord development.
Diving into SQL
When faced with a problem that doesn??™t map neatly to the given abstractions, most
programmers have an instinct to jump down a level. When using ActiveRecord, this
means using raw SQL.
For security as well as performance, it is important to understand the SQL that is
being generated from the commands you issue. ActiveRecord provides a useful
abstraction, but if you are not careful, it will bite you.
The simplest way to drop into raw SQL is to use ActiveRecord::Base.find_by_sql.
This is a very flexible method that returns the same results as find(:all, ...), but
allows you to specify custom SQL. It will even sanitize an array for you:
Person.find_by_sql ["SELECT * FROM people WHERE name LIKE ?", "#{name}%"]
Figure 6-5. Performance comparison between the control and two optimized versions
45.0 44.5 44.0 43.5 43.0 42.5
Before optimization Location optimization Refactoring
Response time per 100 requests (s)
166 | Chapter 6: Performance
The problem with find_by_sql is that it instantiates every object that is returned.
This is usually fine, but sometimes it can be too much overhead. To avoid this, you
may need to bypass ActiveRecord and talk directly with the connection adapter. This
is fairly easy, but you can make it easier by bolting some convenience methods onto
ActiveRecord to sanitize the query automatically:
class <
def select_values(sql)
connection.
Pages:
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