From 84af99e78dbf65b7faa92313acf8457cb0c2b510 Mon Sep 17 00:00:00 2001 From: Daniel Guettler Date: Wed, 9 Jul 2008 14:08:04 +0100 Subject: Ensure NamedScope#build/create/create!/new works as expected when named scope has hash conditions. [Daniel Guettler, Pratik Naik] [#419 state:resolved] Signed-off-by: Pratik Naik --- activerecord/lib/active_record/named_scope.rb | 3 ++- activerecord/test/cases/named_scope_test.rb | 26 ++++++++++++++++++++++++++ activerecord/test/models/topic.rb | 2 ++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index eac61e9e43..080e3d0f5e 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -150,7 +150,8 @@ module ActiveRecord if scopes.include?(method) scopes[method].call(self, *args) else - with_scope :find => proxy_options do + with_scope :find => proxy_options, :create => proxy_options[:conditions].is_a?(Hash) ? proxy_options[:conditions] : {} do + method = :new if method == :build proxy_scope.send(method, *args, &block) end end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 7d73541ee1..0c1eb23428 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -183,4 +183,30 @@ class NamedScopeTest < ActiveRecord::TestCase topics.empty? # use loaded (no query) end end + + def test_should_build_with_proxy_options + topic = Topic.approved.build({}) + assert topic.approved + end + + def test_should_build_new_with_proxy_options + topic = Topic.approved.new + assert topic.approved + end + + def test_should_create_with_proxy_options + topic = Topic.approved.create({}) + assert topic.approved + end + + def test_should_create_with_bang_with_proxy_options + topic = Topic.approved.create!({}) + assert topic.approved + end + + def test_should_build_with_proxy_options_chained + topic = Topic.approved.by_lifo.build({}) + assert topic.approved + assert_equal 'lifo', topic.author_name + end end diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index 47b2eec938..39ca1bf42a 100755 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -4,6 +4,8 @@ class Topic < ActiveRecord::Base { :conditions => ['written_on < ?', time] } } named_scope :approved, :conditions => {:approved => true} + named_scope :by_lifo, :conditions => {:author_name => 'lifo'} + named_scope :approved_as_hash_condition, :conditions => {:topics => {:approved => true}} named_scope 'approved_as_string', :conditions => {:approved => true} named_scope :replied, :conditions => ['replies_count > 0'] -- cgit v1.2.3