Prev | Current Page 387 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


In any case, if you want to work more with SQL and less with Active Record syntax, your
answer is the find_by_sql method. The find_by_sql method simply takes a raw SQL statement
and uses the ActiveRecord::Base.connection.select_all statement to execute the provided
SQL (we talk about the select_all statement in more detail in the next section).
An example helps us to explore this option a bit more??”getting back to our example application,
let??™s pretend that we need to generate a quick report that shows us only what comments
a given user has posted. If we had set up our models with proper associations, we could simply
use that information to access the subset of data. However, we did not set up our models with
proper associations for this section, and since we just want this to be an ad hoc report, we??™ll
use raw SQL and the find_by_sql method to achieve the desired results.
The following example shows our solution using the find_by_sql method:
# Code snippet showing use of find_by_sql method in action
acid = 1 #=> this is the id of the account we are going to generate the report for
pc = Account.


Pages:
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