For example, if you wish to find the
account with the username equal to cpytel you can simply write:
Account.find_by_username("cpytel")
While dynamic finders are fun magic, let??™s be sure not to get ahead of ourselves. Using the
normal find method, the following code would return the same result as the dynamic finder:
Account.find(:all, :conditions => ["username = ?", "cpytel"])
CHAPTER 1 ?– INTRODUCING ACTIVE RECORD 21
?– Note A lot of Active Record magic, such as dynamic finders, is made possible by using the Ruby??™s
method_missing function; method_missing allows you to handle situations when a message is sent to an
object for which it doesn??™t have a method. The method find_by_username doesn??™t exist in the code anywhere,
so it is being handled by method_missing.
Once we??™ve retrieved an Active Record object, say with
account = Account.find_by_username("cpytel")
we can delete the associated record from the database by calling this method:
account.destroy
When you use the destroy method listed here, you are really only executing a SQL delete
statement within your database.
Pages:
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