From d52ee204bfeae5e95a6fb086643fe513bd5da07f Mon Sep 17 00:00:00 2001 From: Nik Wakelin Date: Mon, 23 Jun 2008 10:14:33 +1200 Subject: [PATCH] Added syntactic sugar to belongs_to associations in ActiveRecord hash conditions --- activerecord/lib/active_record/base.rb | 14 ++++++++++++++ activerecord/test/cases/finder_test.rb | 10 ++++++++++ 2 files changed, 24 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 8fca34e..0fb9254 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -196,6 +196,10 @@ module ActiveRecord #:nodoc: # # Student.find(:all, :conditions => { :grade => [9,11,12] }) # + # You can also use assocation names for belongs_to assocations. For example, if Student belongs_to University + # + # Student.find(:all, :conditions => { :university => victoria_wellington }) + # # == Overwriting default accessors # # All column values are automatically available through basic accessors on the Active Record object, but sometimes you @@ -2002,6 +2006,9 @@ module ActiveRecord #:nodoc: # And for value objects on a composed_of relationship: # { :address => Address.new("123 abc st.", "chicago") } # # => "address_street='123 abc st.' and address_city='chicago'" + # There's also some sugar built in for belongs_to associations + # { :person => 4 } + # # => "person_id= 4" def sanitize_sql_hash_for_conditions(attrs) attrs = expand_hash_conditions_for_aggregates(attrs) @@ -2015,6 +2022,13 @@ module ActiveRecord #:nodoc: else table_name = quoted_table_name end + + unless column_names.include?(attr) + # Lookup the foreign key for belongs_to associations + if reflection = reflect_on_all_associations(:belongs_to).find { |a| a.name.to_s == attr } + attr = reflection.association_foreign_key + end + end "#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}" end.join(' AND ') diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 80936d5..7131173 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -207,6 +207,16 @@ class FinderTest < ActiveRecord::TestCase } end + def test_find_on_hash_conditions_with_belongs_to_sugar + david = authors(:david) + assert Post.find(:first, :conditions => { :author => david }) + + # test we still fall through + assert_raises(ActiveRecord::StatementInvalid) do + Post.find(:first, :conditions => { :this_is_not_a_column_name => "fubar"}) + end + end + def test_find_on_association_proxy_conditions assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10], Comment.find_all_by_post_id(authors(:david).posts).map(&:id).sort end -- 1.5.3.7