aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/query_methods.rb
diff options
context:
space:
mode:
authorbeerlington <pete@lette.us>2012-09-11 14:11:51 -0400
committerbeerlington <pete@lette.us>2012-09-11 14:11:51 -0400
commit3da275c4396d7fad250d2b786027ba4f14344bd4 (patch)
treea0367f680705af28ea053e890f82b359fa511a11 /activerecord/lib/active_record/relation/query_methods.rb
parentf2a44ade14f995d0574bedf79c8d1bee520f0306 (diff)
downloadrails-3da275c4396d7fad250d2b786027ba4f14344bd4.tar.gz
rails-3da275c4396d7fad250d2b786027ba4f14344bd4.tar.bz2
rails-3da275c4396d7fad250d2b786027ba4f14344bd4.zip
Accept belongs_to assoc. keys in ActiveRecord queries
Allows you to specify the model association key in a belongs_to relationship instead of the foreign key. The following queries are now equivalent: Post.where(:author_id => Author.first) Post.where(:author => Author.first) PriceEstimate.where(:estimate_of_type => 'Treasure', :estimate_of_id => treasure) PriceEstimate.where(:estimate_of => treasure)
Diffstat (limited to 'activerecord/lib/active_record/relation/query_methods.rb')
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb18
1 files changed, 18 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index f6bacf4822..00cdaf686f 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -340,6 +340,24 @@ module ActiveRecord
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
#
+ # In the case of a belongs_to relationship, an association key can be used
+ # to specify the model if an ActiveRecord object is used as the value.
+ #
+ # author = Author.find(1)
+ #
+ # # The following queries will be equivalent:
+ # Post.where(:author => author)
+ # Post.where(:author_id => author)
+ #
+ # This also works with polymorphic belongs_to relationships:
+ #
+ # treasure = Treasure.create(:name => 'gold coins')
+ # treasure.price_estimates << PriceEstimate.create(:price => 125)
+ #
+ # # The following queries will be equivalent:
+ # PriceEstimate.where(:estimate_of => treasure)
+ # PriceEstimate.where(:estimate_of_type => 'Treasure', :estimate_of_id => treasure)
+ #
# === Joins
#
# If the relation is the result of a join, you may create a condition which uses any of the