From ac8fd7dfb91eb0e554537e671eaf1615a1d19757 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 2 Jan 2005 13:31:00 +0000 Subject: Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@307 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/lib/active_record/base.rb | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 63810d3c41..cc61498a94 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -97,6 +97,17 @@ module ActiveRecord #:nodoc: # end # end # + # == Dynamic attribute-based finders + # + # Dynamic attribute-based finders are a cleaner way of getting objects by simple queries without turning to SQL. They work by + # appending the name of an attribute to find_by_, so you get finders like Person.find_by_user_name, Payment.find_by_transaction_id. + # So instead of writing Person.find_first(["user_name = ?", user_name]), you just do Person.find_by_user_name(user_name). + # + # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like + # Person.find_by_user_name_and_password or even Payment.find_by_purchaser_and_state_and_country. So instead of writing + # Person.find_first(["user_name = ? AND password = ?", user_name, password]), you just do + # Person.find_by_user_name_and_password(user_name, password). + # # == Saving arrays, hashes, and other non-mappeable objects in text columns # # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+. @@ -636,6 +647,20 @@ module ActiveRecord #:nodoc: return table_name end + # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into + # find_first(["user_name = ?", user_name]) and find_first(["user_name = ? AND password = ?", user_name, password]) respectively. + def method_missing(method_id, *arguments) + method_name = method_id.id2name + + if method_name =~ /find_by_([_a-z]+)/ + attributes = $1.split("_and_") + attributes.each { |attr_name| super unless column_methods_hash[attr_name.intern] } + conditions = attributes.collect { |attr_name| "#{attr_name} = ? "}.join(" AND ") + find_first([conditions, *arguments]) + else + super + end + end protected def subclasses -- cgit v1.2.3