aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionpack/CHANGELOG.md8
-rw-r--r--actionpack/lib/action_controller/test_case.rb32
-rw-r--r--actionpack/lib/action_dispatch/http/headers.rb3
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb5
-rw-r--r--actionpack/test/controller/test_case_test.rb22
-rw-r--r--actionpack/test/dispatch/header_test.rb22
-rw-r--r--activemodel/CHANGELOG.md2
-rw-r--r--activemodel/test/cases/attribute_methods_test.rb2
-rw-r--r--activemodel/test/cases/naming_test.rb2
-rw-r--r--activemodel/test/cases/validations_test.rb4
-rw-r--r--activerecord/CHANGELOG.md35
-rw-r--r--activerecord/activerecord.gemspec2
-rw-r--r--activerecord/lib/active_record/associations.rb1
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb2
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb18
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb7
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many_through.rb2
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/schema_cache.rb42
-rw-r--r--activerecord/lib/active_record/core.rb8
-rw-r--r--activerecord/lib/active_record/counter_cache.rb3
-rw-r--r--activerecord/lib/active_record/model_schema.rb2
-rw-r--r--activerecord/lib/active_record/querying.rb2
-rw-r--r--activerecord/lib/active_record/relation.rb16
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb11
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb20
-rw-r--r--activerecord/test/cases/adapters/postgresql/quoting_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/uuid_test.rb43
-rw-r--r--activerecord/test/cases/associations/cascaded_eager_loading_test.rb2
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb2
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb2
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb4
-rw-r--r--activerecord/test/cases/associations/nested_through_associations_test.rb2
-rw-r--r--activerecord/test/cases/associations_test.rb5
-rw-r--r--activerecord/test/cases/base_test.rb12
-rw-r--r--activerecord/test/cases/calculations_test.rb21
-rw-r--r--activerecord/test/cases/connection_adapters/schema_cache_test.rb41
-rw-r--r--activerecord/test/cases/counter_cache_test.rb7
-rw-r--r--activerecord/test/cases/finder_test.rb2
-rw-r--r--activerecord/test/cases/relation_test.rb12
-rw-r--r--activerecord/test/cases/relations_test.rb24
-rw-r--r--activerecord/test/models/author.rb8
-rw-r--r--activerecord/test/models/book.rb2
-rw-r--r--activerecord/test/models/liquid.rb3
-rw-r--r--activerecord/test/models/project.rb8
-rw-r--r--activesupport/lib/active_support/tagged_logging.rb8
-rw-r--r--activesupport/test/tagged_logging_test.rb11
-rw-r--r--guides/source/active_record_querying.md11
-rw-r--r--guides/source/getting_started.md2
-rw-r--r--guides/source/testing.md15
-rw-r--r--railties/CHANGELOG.md4
-rw-r--r--railties/lib/rails/application/bootstrap.rb6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb2
-rw-r--r--railties/lib/rails/test_unit/testing.rake1
-rw-r--r--railties/test/application/configuration_test.rb21
59 files changed, 463 insertions, 136 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 3eb40a586e..b23d0668d3 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,13 +1,17 @@
## Rails 4.0.0 (unreleased) ##
-* `ActionDispatch::IntegrationTest` allows headers and rack env
+* Integration and functional tests allow headers and rack env
variables to be passed when performing requests.
Fixes #6513.
Example:
+ # integration test
get "/success", {}, "HTTP_REFERER" => "http://test.com/",
- "Host" => "http://test.com"
+ "Accepts" => "text/plain, text/html"
+
+ # functional test
+ @request.headers["Accepts"] = "text/plain, text/html"
*Yves Senn*
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 9dae78d25d..41b5228872 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -451,37 +451,55 @@ module ActionController
end
- # Executes a request simulating GET HTTP method and set/volley the response
+ # Simulate a GET request with the given parameters.
+ #
+ # - +action+: The controller action to call.
+ # - +parameters+: The HTTP parameters that you want to pass. This may
+ # be +nil+, a Hash, or a String that is appropriately encoded
+ # (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
+ # - +session+: A Hash of parameters to store in the session. This may be +nil+.
+ # - +flash+: A Hash of parameters to store in the flash. This may be +nil+.
+ #
+ # You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with
+ # +#post+, +#patch+, +#put+, +#delete+, and +#head+.
+ # Note that the request method is not verified. The different methods are
+ # available to make the tests more expressive.
def get(action, *args)
process(action, "GET", *args)
end
- # Executes a request simulating POST HTTP method and set/volley the response
+ # Simulate a POST request with the given parameters and set/volley the response.
+ # See +#get+ for more details.
def post(action, *args)
process(action, "POST", *args)
end
- # Executes a request simulating PATCH HTTP method and set/volley the response
+ # Simulate a PATCH request with the given parameters and set/volley the response.
+ # See +#get+ for more details.
def patch(action, *args)
process(action, "PATCH", *args)
end
- # Executes a request simulating PUT HTTP method and set/volley the response
+ # Simulate a PUT request with the given parameters and set/volley the response.
+ # See +#get+ for more details.
def put(action, *args)
process(action, "PUT", *args)
end
- # Executes a request simulating DELETE HTTP method and set/volley the response
+ # Simulate a DELETE request with the given parameters and set/volley the response.
+ # See +#get+ for more details.
def delete(action, *args)
process(action, "DELETE", *args)
end
- # Executes a request simulating HEAD HTTP method and set/volley the response
+ # Simulate a HEAD request with the given parameters and set/volley the response.
+ # See +#get+ for more details.
def head(action, *args)
process(action, "HEAD", *args)
end
- # Executes a request simulating OPTIONS HTTP method and set/volley the response
+ # Simulate a OPTIONS request with the given parameters and set/volley the response.
+ # See +#get+ for more details.
def options(action, *args)
process(action, "OPTIONS", *args)
end
diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb
index 1574518a16..2666cd4b0a 100644
--- a/actionpack/lib/action_dispatch/http/headers.rb
+++ b/actionpack/lib/action_dispatch/http/headers.rb
@@ -15,8 +15,7 @@ module ActionDispatch
attr_reader :env
def initialize(env = {})
- @env = {}
- merge!(env)
+ @env = env
end
def [](key)
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index ae1b0b5dea..56c31255f3 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -269,7 +269,6 @@ module ActionDispatch
# Performs the actual request.
def process(method, path, parameters = nil, headers_or_env = nil)
- rack_env = Http::Headers.new(headers_or_env || {}).env
if path =~ %r{://}
location = URI.parse(path)
https! URI::HTTPS === location if location.scheme
@@ -300,10 +299,12 @@ module ActionDispatch
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
"HTTP_ACCEPT" => accept
}
+ # this modifies the passed env directly
+ Http::Headers.new(env).merge!(headers_or_env || {})
session = Rack::Test::Session.new(_mock_session)
- env.merge!(rack_env)
+ env.merge!(env)
# NOTE: rack-test v0.5 doesn't build a default uri correctly
# Make sure requested path is always a full uri
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index df31338f09..9c6d02a62d 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -57,6 +57,10 @@ class TestCaseTest < ActionController::TestCase
render :text => request.protocol
end
+ def test_headers
+ render text: JSON.dump(request.headers.env)
+ end
+
def test_html_output
render :text => <<HTML
<html>
@@ -626,6 +630,24 @@ XML
assert_equal 2004, page[:year]
end
+ test "set additional HTTP headers" do
+ @request.headers['Referer'] = "http://nohost.com/home"
+ @request.headers['Content-Type'] = "application/rss+xml"
+ get :test_headers
+ parsed_env = JSON.parse(@response.body)
+ assert_equal "http://nohost.com/home", parsed_env["HTTP_REFERER"]
+ assert_equal "application/rss+xml", parsed_env["CONTENT_TYPE"]
+ end
+
+ test "set additional env variables" do
+ @request.headers['HTTP_REFERER'] = "http://example.com/about"
+ @request.headers['CONTENT_TYPE'] = "application/json"
+ get :test_headers
+ parsed_env = JSON.parse(@response.body)
+ assert_equal "http://example.com/about", parsed_env["HTTP_REFERER"]
+ assert_equal "application/json", parsed_env["CONTENT_TYPE"]
+ end
+
def test_id_converted_to_string
get :test_params, :id => 20, :foo => Object.new
assert_kind_of String, @request.path_parameters['id']
diff --git a/actionpack/test/dispatch/header_test.rb b/actionpack/test/dispatch/header_test.rb
index 3bb3b3db23..9e37b96951 100644
--- a/actionpack/test/dispatch/header_test.rb
+++ b/actionpack/test/dispatch/header_test.rb
@@ -8,15 +8,15 @@ class HeaderTest < ActiveSupport::TestCase
)
end
- test "#new with mixed headers and env" do
+ test "#new does not normalize the data" do
headers = ActionDispatch::Http::Headers.new(
"Content-Type" => "application/json",
"HTTP_REFERER" => "/some/page",
"Host" => "http://test.com")
- assert_equal({"CONTENT_TYPE" => "application/json",
+ assert_equal({"Content-Type" => "application/json",
"HTTP_REFERER" => "/some/page",
- "HTTP_HOST" => "http://test.com"}, headers.env)
+ "Host" => "http://test.com"}, headers.env)
end
test "#env returns the headers as env variables" do
@@ -117,11 +117,21 @@ class HeaderTest < ActiveSupport::TestCase
end
test "symbols are treated as strings" do
- headers = ActionDispatch::Http::Headers.new(:SERVER_NAME => "example.com",
- "HTTP_REFERER" => "/",
- :Host => "test.com")
+ headers = ActionDispatch::Http::Headers.new
+ headers.merge!(:SERVER_NAME => "example.com",
+ "HTTP_REFERER" => "/",
+ :Host => "test.com")
assert_equal "example.com", headers["SERVER_NAME"]
assert_equal "/", headers[:HTTP_REFERER]
assert_equal "test.com", headers["HTTP_HOST"]
end
+
+ test "headers directly modifies the passed environment" do
+ env = {"HTTP_REFERER" => "/"}
+ headers = ActionDispatch::Http::Headers.new(env)
+ headers['Referer'] = "http://example.com/"
+ headers.merge! "CONTENT_TYPE" => "text/plain"
+ assert_equal({"HTTP_REFERER"=>"http://example.com/",
+ "CONTENT_TYPE"=>"text/plain"}, env)
+ end
end
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index c6d7b0b5d3..6ba0c7cd6b 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -111,7 +111,7 @@
* Changed `ActiveModel::Serializers::Xml::Serializer#add_associations` to by default
propagate `:skip_types, :dasherize, :camelize` keys to included associations.
- It can be overriden on each association by explicitly specifying the option on one
+ It can be overridden on each association by explicitly specifying the option on one
or more associations
*Anthony Alberto*
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
index baaf842222..d3ec78157c 100644
--- a/activemodel/test/cases/attribute_methods_test.rb
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -194,7 +194,7 @@ class AttributeMethodsTest < ActiveModel::TestCase
assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
end
- test 'acessing a suffixed attribute' do
+ test 'accessing a suffixed attribute' do
m = ModelWithAttributes2.new
m.attributes = { 'foo' => 'bar' }
diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb
index 38ba3cc152..aa683f4152 100644
--- a/activemodel/test/cases/naming_test.rb
+++ b/activemodel/test/cases/naming_test.rb
@@ -245,7 +245,7 @@ class NamingHelpersTest < ActiveModel::TestCase
end
def test_uncountable
- assert uncountable?(@uncountable), "Expected 'sheep' to be uncoutable"
+ assert uncountable?(@uncountable), "Expected 'sheep' to be uncountable"
assert !uncountable?(@klass), "Expected 'contact' to be countable"
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index a9d32808da..d3723fa45b 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -213,7 +213,7 @@ class ValidationsTest < ActiveModel::TestCase
assert_equal 'is too short (minimum is 2 characters)', t.errors[key][0]
end
- def test_validaton_with_if_and_on
+ def test_validation_with_if_and_on
Topic.validates_presence_of :title, :if => Proc.new{|x| x.author_name = "bad"; true }, :on => :update
t = Topic.new(:title => "")
@@ -361,7 +361,7 @@ class ValidationsTest < ActiveModel::TestCase
def test_dup_validity_is_independent
Topic.validates_presence_of :title
- topic = Topic.new("title" => "Litterature")
+ topic = Topic.new("title" => "Literature")
topic.valid?
duped = topic.dup
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index f73fc9d9a3..a8151cd23e 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,5 +1,40 @@
## Rails 4.0.0 (unreleased) ##
+* Referencing join tables implicitly was deprecated. There is a
+ possibility that these deprecation warnings are shown even if you
+ don't make use of that feature. You can now disable the feature entirely.
+ Fixes #9712.
+
+ Example:
+
+ # in your configuration
+ config.active_record.disable_implicit_join_references = true
+
+ # or directly
+ ActiveRecord::Base.disable_implicit_join_references = true
+
+ *Yves Senn*
+
+* The `:distinct` option for `Relation#count` is deprecated. You
+ should use `Relation#distinct` instead.
+
+ Example:
+
+ # Before
+ Post.select(:author_name).count(distinct: true)
+
+ # After
+ Post.select(:author_name).distinct.count
+
+ *Yves Senn*
+
+* Rename `Relation#uniq` to `Relation#distinct`. `#uniq` is still
+ available as an alias but we encourage to use `#distinct` instead.
+ Also `Relation#uniq_value` is aliased to `Relation#distinct_value`,
+ this is a temporary solution and you should migrate to `distinct_value`.
+
+ *Yves Senn*
+
* Fix quoting for sqlite migrations using copy_table_contents() with binary
columns.
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index 89a62f0873..3e3475f709 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -24,6 +24,6 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
s.add_dependency 'activemodel', version
- s.add_dependency 'arel', '~> 4.0.0.beta1'
+ s.add_dependency 'arel', '~> 4.0.0.beta2'
s.add_dependency 'activerecord-deprecated_finders', '~> 0.0.3'
end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 06da5f2e0d..0c670bdaa1 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -241,6 +241,7 @@ module ActiveRecord
# others.destroy_all | X | X | X
# others.find(*args) | X | X | X
# others.exists? | X | X | X
+ # others.distinct | X | X | X
# others.uniq | X | X | X
# others.reset | X | X | X
#
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index c5fb1fe2c7..a9525436fb 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -22,7 +22,7 @@ module ActiveRecord
private
def column_for(table_name, column_name)
- columns = alias_tracker.connection.schema_cache.columns_hash[table_name]
+ columns = alias_tracker.connection.schema_cache.columns_hash(table_name)
columns[column_name]
end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index c992f51dbb..906560bd44 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -34,7 +34,7 @@ module ActiveRecord
reload
end
- CollectionProxy.new(klass, self)
+ @proxy ||= CollectionProxy.new(klass, self)
end
# Implements the writer method, e.g. foo.items= for Foo.has_many :items
@@ -174,13 +174,14 @@ module ActiveRecord
reflection.klass.count_by_sql(custom_counter_sql)
else
- if association_scope.uniq_value
+ relation = scope
+ if association_scope.distinct_value
# This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
column_name ||= reflection.klass.primary_key
- count_options[:distinct] = true
+ relation = relation.distinct
end
- value = scope.count(column_name, count_options)
+ value = relation.count(column_name)
limit = options[:limit]
offset = options[:offset]
@@ -246,14 +247,14 @@ module ActiveRecord
# +count_records+, which is a method descendants have to provide.
def size
if !find_target? || loaded?
- if association_scope.uniq_value
+ if association_scope.distinct_value
target.uniq.size
else
target.size
end
elsif !loaded? && !association_scope.group_values.empty?
load_target.size
- elsif !loaded? && !association_scope.uniq_value && target.is_a?(Array)
+ elsif !loaded? && !association_scope.distinct_value && target.is_a?(Array)
unsaved_records = target.select { |r| r.new_record? }
unsaved_records.size + count_records
else
@@ -306,12 +307,13 @@ module ActiveRecord
end
end
- def uniq
+ def distinct
seen = {}
load_target.find_all do |record|
seen[record.id] = true unless seen.key?(record.id)
end
end
+ alias uniq distinct
# Replace this collection with +other_array+. This will perform a diff
# and delete/add only records that have changed.
@@ -352,7 +354,7 @@ module ActiveRecord
callback(:before_add, record)
yield(record) if block_given?
- if association_scope.uniq_value && index = @target.index(record)
+ if association_scope.distinct_value && index = @target.index(record)
@target[index] = record
else
@target << record
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 543204abac..c2add32aa6 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -649,11 +649,12 @@ module ActiveRecord
# # #<Pet name: "Fancy-Fancy">
# # ]
#
- # person.pets.select(:name).uniq
+ # person.pets.select(:name).distinct
# # => [#<Pet name: "Fancy-Fancy">]
- def uniq
- @association.uniq
+ def distinct
+ @association.distinct
end
+ alias uniq distinct
# Count all records using SQL.
#
diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
index 9a662d3f53..38bc7ce7da 100644
--- a/activerecord/lib/active_record/associations/preloader/has_many_through.rb
+++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
@@ -6,7 +6,7 @@ module ActiveRecord
def associated_records_by_owner
super.each do |owner, records|
- records.uniq! if reflection_scope.uniq_value
+ records.uniq! if reflection_scope.distinct_value
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
index 3e454b713a..931209b07b 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -90,7 +90,7 @@ module ActiveRecord
base_name.foreign_key
else
if ActiveRecord::Base != self && table_exists?
- connection.schema_cache.primary_keys[table_name]
+ connection.schema_cache.primary_keys(table_name)
else
'id'
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index 805832f01e..9c659dd0af 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -24,11 +24,16 @@ module ActiveRecord
base.type_to_sql(type.to_sym, limit, precision, scale)
end
+ def primary_key?
+ type == :primary_key
+ end
+
def to_sql
column_sql = "#{base.quote_column_name(name)} #{sql_type}"
column_options = {}
column_options[:null] = null unless null.nil?
column_options[:default] = default unless default.nil?
+ column_options[:column] = self
add_column_options!(column_sql, column_options) unless type.to_sym == :primary_key
column_sql
end
@@ -36,7 +41,7 @@ module ActiveRecord
private
def add_column_options!(sql, options)
- base.add_column_options!(sql, options.merge(:column => self))
+ base.add_column_options!(sql, options)
end
end
@@ -298,7 +303,7 @@ module ActiveRecord
end
def primary_key_column_name
- primary_key_column = columns.detect { |c| c.type == :primary_key }
+ primary_key_column = columns.detect { |c| c.primary_key? }
primary_key_column && primary_key_column.name
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index b8b2cf9ab1..cd4409295f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -172,7 +172,14 @@ module ActiveRecord
# See also TableDefinition#column for details on how to create columns.
def create_table(table_name, options = {})
td = create_table_definition
- td.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false
+
+ unless options[:id] == false
+ pk = options.fetch(:primary_key) {
+ Base.get_primary_key table_name.to_s.singularize
+ }
+
+ td.primary_key pk
+ end
yield td if block_given?
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
index 47e2e3928f..43f991b362 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
@@ -51,9 +51,12 @@ module ActiveRecord
super
end
when Numeric
- return super unless column.sql_type == 'money'
- # Not truly string input, so doesn't require (or allow) escape string syntax.
- "'#{value}'"
+ if column.sql_type == 'money' || [:string, :text].include?(column.type)
+ # Not truly string input, so doesn't require (or allow) escape string syntax.
+ "'#{value}'"
+ else
+ super
+ end
when String
case column.sql_type
when 'bytea' then "'#{escape_bytea(value)}'"
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index eb541b0215..dfa4c3967a 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -632,7 +632,13 @@ module ActiveRecord
if options[:array] || options[:column].try(:array)
sql << '[]'
end
- super
+
+ column = options.fetch(:column) { return super }
+ if column.type == :uuid && options[:default] =~ /\(\)/
+ sql << " DEFAULT #{options[:default]}"
+ else
+ super
+ end
end
# Set the authorized user for this session
diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
index 5839d1d3b4..1d7a22e831 100644
--- a/activerecord/lib/active_record/connection_adapters/schema_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
@@ -1,7 +1,9 @@
+require 'active_support/deprecation/reporting'
+
module ActiveRecord
module ConnectionAdapters
class SchemaCache
- attr_reader :primary_keys, :tables, :version
+ attr_reader :version
attr_accessor :connection
def initialize(conn)
@@ -14,6 +16,15 @@ module ActiveRecord
prepare_default_proc
end
+ def primary_keys(table_name = nil)
+ if table_name
+ @primary_keys[table_name]
+ else
+ ActiveSupport::Deprecation.warn('call primary_keys with a table name!')
+ @primary_keys.dup
+ end
+ end
+
# A cached lookup for table existence.
def table_exists?(name)
return @tables[name] if @tables.key? name
@@ -30,12 +41,22 @@ module ActiveRecord
end
end
+ def tables(name = nil)
+ if name
+ @tables[name]
+ else
+ ActiveSupport::Deprecation.warn('call tables with a name!')
+ @tables.dup
+ end
+ end
+
# Get the columns for a table
def columns(table = nil)
if table
@columns[table]
else
- @columns
+ ActiveSupport::Deprecation.warn('call columns with a table name!')
+ @columns.dup
end
end
@@ -45,7 +66,8 @@ module ActiveRecord
if table
@columns_hash[table]
else
- @columns_hash
+ ActiveSupport::Deprecation.warn('call columns_hash with a table name!')
+ @columns_hash.dup
end
end
@@ -58,6 +80,12 @@ module ActiveRecord
@version = nil
end
+ def size
+ [@columns, @columns_hash, @primary_keys, @tables].map { |x|
+ x.size
+ }.inject :+
+ end
+
# Clear out internal caches for table with +table_name+.
def clear_table_cache!(table_name)
@columns.delete table_name
@@ -69,9 +97,9 @@ module ActiveRecord
def marshal_dump
# if we get current version during initialization, it happens stack over flow.
@version = ActiveRecord::Migrator.current_version
- [@version] + [:@columns, :@columns_hash, :@primary_keys, :@tables].map do |val|
- self.instance_variable_get(val).inject({}) { |h, v| h[v[0]] = v[1]; h }
- end
+ [@version] + [@columns, @columns_hash, @primary_keys, @tables].map { |val|
+ Hash[val]
+ }
end
def marshal_load(array)
@@ -87,7 +115,7 @@ module ActiveRecord
end
@columns_hash.default_proc = Proc.new do |h, table_name|
- h[table_name] = Hash[columns[table_name].map { |col|
+ h[table_name] = Hash[columns(table_name).map { |col|
[col.name, col]
}]
end
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 72371be657..aa56219755 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -69,6 +69,14 @@ module ActiveRecord
mattr_accessor :timestamped_migrations, instance_writer: false
self.timestamped_migrations = true
+ ##
+ # :singleton-method:
+ # Disable implicit join references. This feature was deprecated with Rails 4.
+ # If you don't make use of implicit references but still see deprecation warnings
+ # you can disable the feature entirely. This will be the default with Rails 4.1.
+ mattr_accessor :disable_implicit_join_references, instance_writer: false
+ self.disable_implicit_join_references = false
+
class_attribute :connection_handler, instance_writer: false
self.connection_handler = ConnectionAdapters::ConnectionHandler.new
end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index 81f92db271..81cca37939 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -11,7 +11,7 @@ module ActiveRecord
# ==== Parameters
#
# * +id+ - The id of the object you wish to reset a counter on.
- # * +counters+ - One or more counter names to reset
+ # * +counters+ - One or more association counters to reset
#
# ==== Examples
#
@@ -21,6 +21,7 @@ module ActiveRecord
object = find(id)
counters.each do |association|
has_many_association = reflect_on_association(association.to_sym)
+ raise ArgumentError, "'#{self.name}' has no association called '#{association}'" unless has_many_association
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
has_many_association = has_many_association.through_reflection
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index 85fb4be992..ac2d2f2712 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -205,7 +205,7 @@ module ActiveRecord
# Returns an array of column objects for the table associated with this class.
def columns
- @columns ||= connection.schema_cache.columns[table_name].map do |col|
+ @columns ||= connection.schema_cache.columns(table_name).map do |col|
col = col.dup
col.primary = (col.name == primary_key)
col
diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb
index e04a3d0976..902fd90c54 100644
--- a/activerecord/lib/active_record/querying.rb
+++ b/activerecord/lib/active_record/querying.rb
@@ -8,7 +8,7 @@ module ActiveRecord
delegate :find_each, :find_in_batches, :to => :all
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
:where, :preload, :eager_load, :includes, :from, :lock, :readonly,
- :having, :create_with, :uniq, :references, :none, :to => :all
+ :having, :create_with, :uniq, :distinct, :references, :none, :to => :all
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :ids, :to => :all
# Executes a custom SQL query against your database and returns all the results. The results will
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index ad54ba55b6..037097d2dd 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -10,7 +10,7 @@ module ActiveRecord
:extending]
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
- :reverse_order, :uniq, :create_with]
+ :reverse_order, :distinct, :create_with]
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
@@ -506,6 +506,12 @@ module ActiveRecord
includes_values & joins_values
end
+ # +uniq+ and +uniq!+ are silently deprecated. +uniq_value+ delegates to +distinct_value+
+ # to maintain backwards compatibility. Use +distinct_value+ instead.
+ def uniq_value
+ distinct_value
+ end
+
# Compares two relations for equality.
def ==(other)
case other
@@ -589,7 +595,8 @@ module ActiveRecord
if (references_values - joined_tables).any?
true
- elsif (string_tables - joined_tables).any?
+ elsif !ActiveRecord::Base.disable_implicit_join_references &&
+ (string_tables - joined_tables).any?
ActiveSupport::Deprecation.warn(
"It looks like you are eager loading table(s) (one of: #{string_tables.join(', ')}) " \
"that are referenced in a string SQL snippet. For example: \n" \
@@ -603,7 +610,10 @@ module ActiveRecord
"From now on, you must explicitly tell Active Record when you are referencing a table " \
"from a string:\n" \
"\n" \
- " Post.includes(:comments).where(\"comments.title = 'foo'\").references(:comments)\n\n"
+ " Post.includes(:comments).where(\"comments.title = 'foo'\").references(:comments)\n" \
+ "\n" \
+ "If you don't rely on implicit join references you can disable the feature entirely" \
+ "by setting `config.active_record.disable_implicit_join_references = true`."
)
true
else
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 7f95181c67..be011b22af 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -11,7 +11,7 @@ module ActiveRecord
# Person.count(:all)
# # => performs a COUNT(*) (:all is an alias for '*')
#
- # Person.count(:age, distinct: true)
+ # Person.distinct.count(:age)
# # => counts the number of different age values
#
# If +count+ is used with +group+, it returns a Hash whose keys represent the aggregated column,
@@ -198,8 +198,13 @@ module ActiveRecord
def perform_calculation(operation, column_name, options = {})
operation = operation.to_s.downcase
- # If #count is used in conjuction with #uniq it is considered distinct. (eg. relation.uniq.count)
- distinct = options[:distinct] || self.uniq_value
+ # If #count is used with #distinct / #uniq it is considered distinct. (eg. relation.distinct.count)
+ distinct = self.distinct_value
+ if options.has_key?(:distinct)
+ ActiveSupport::Deprecation.warn "The :distinct option for `Relation#count` is deprecated. " \
+ "Please use `Relation#distinct` instead. (eg. `relation.distinct.count`)"
+ distinct = options[:distinct]
+ end
if operation == "count"
column_name ||= (select_for_count || :all)
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index b7960936cf..10a31109d5 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -710,20 +710,22 @@ module ActiveRecord
# User.select(:name)
# # => Might return two records with the same name
#
- # User.select(:name).uniq
- # # => Returns 1 record per unique name
+ # User.select(:name).distinct
+ # # => Returns 1 record per distinct name
#
- # User.select(:name).uniq.uniq(false)
+ # User.select(:name).distinct.distinct(false)
# # => You can also remove the uniqueness
- def uniq(value = true)
- spawn.uniq!(value)
+ def distinct(value = true)
+ spawn.distinct!(value)
end
+ alias uniq distinct
- # Like #uniq, but modifies relation in place.
- def uniq!(value = true) # :nodoc:
- self.uniq_value = value
+ # Like #distinct, but modifies relation in place.
+ def distinct!(value = true) # :nodoc:
+ self.distinct_value = value
self
end
+ alias uniq! distinct!
# Used to extend a scope with additional methods, either through
# a module or through a block provided.
@@ -814,7 +816,7 @@ module ActiveRecord
build_select(arel, select_values.uniq)
- arel.distinct(uniq_value)
+ arel.distinct(distinct_value)
arel.from(build_from) if from_value
arel.lock(lock_value) if lock_value
diff --git a/activerecord/test/cases/adapters/postgresql/quoting_test.rb b/activerecord/test/cases/adapters/postgresql/quoting_test.rb
index 685f0ea74f..b3429648ee 100644
--- a/activerecord/test/cases/adapters/postgresql/quoting_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/quoting_test.rb
@@ -44,6 +44,14 @@ module ActiveRecord
c = Column.new(nil, 1, 'float')
assert_equal "'Infinity'", @conn.quote(infinity, c)
end
+
+ def test_quote_cast_numeric
+ fixnum = 666
+ c = Column.new(nil, nil, 'string')
+ assert_equal "'666'", @conn.quote(fixnum, c)
+ c = Column.new(nil, nil, 'text')
+ assert_equal "'666'", @conn.quote(fixnum, c)
+ end
end
end
end
diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
new file mode 100644
index 0000000000..53002c5265
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
@@ -0,0 +1,43 @@
+# encoding: utf-8
+
+require "cases/helper"
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlUUIDTest < ActiveRecord::TestCase
+ class UUID < ActiveRecord::Base
+ self.table_name = 'pg_uuids'
+ end
+
+ def setup
+ @connection = ActiveRecord::Base.connection
+
+ unless @connection.supports_extensions?
+ return skip "do not test on PG without uuid-ossp"
+ end
+
+ unless @connection.extension_enabled?('uuid-ossp')
+ @connection.enable_extension 'uuid-ossp'
+ @connection.commit_db_transaction
+ end
+
+ @connection.reconnect!
+
+ @connection.transaction do
+ @connection.create_table('pg_uuids', id: :uuid) do |t|
+ t.string 'name'
+ t.uuid 'other_uuid', default: 'uuid_generate_v4()'
+ end
+ end
+ end
+
+ def teardown
+ @connection.execute 'drop table if exists pg_uuids'
+ end
+
+ def test_auto_create_uuid
+ u = UUID.create
+ u.reload
+ assert_not_nil u.other_uuid
+ end
+end
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
index 80bca7f63e..e693d34f99 100644
--- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -55,7 +55,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
assert_nothing_raised do
assert_equal 4, categories.count
assert_equal 4, categories.to_a.count
- assert_equal 3, categories.count(:distinct => true)
+ assert_equal 3, categories.distinct.count
assert_equal 3, categories.to_a.uniq.size # Must uniq since instantiating with inner joins will get dupes
end
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 1b1b479f1a..84bdca3a97 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -316,7 +316,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
dev.projects << projects(:active_record)
assert_equal 3, dev.projects.size
- assert_equal 1, dev.projects.uniq.size
+ assert_equal 1, dev.projects.distinct.size
end
def test_uniq_before_the_fact
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 4f246f575e..918783e8f1 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -82,7 +82,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
- authors_with_welcoming_post_titles = Author.all.merge!(:joins => :posts, :where => "posts.title like 'Welcome%'").calculate(:count, 'authors.id', :distinct => true)
+ authors_with_welcoming_post_titles = Author.all.merge!(joins: :posts, where: "posts.title like 'Welcome%'").distinct.calculate(:count, 'authors.id')
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 10ec33be75..c05481dd91 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -397,14 +397,14 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_through_polymorphic_has_many
- assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.uniq.sort_by { |t| t.id }
+ assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.distinct.sort_by { |t| t.id }
end
def test_include_has_many_through_polymorphic_has_many
author = Author.includes(:taggings).find authors(:david).id
expected_taggings = taggings(:welcome_general, :thinking_general)
assert_no_queries do
- assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
+ assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id }
end
end
diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb
index e355ed3495..e75d43bda8 100644
--- a/activerecord/test/cases/associations/nested_through_associations_test.rb
+++ b/activerecord/test/cases/associations/nested_through_associations_test.rb
@@ -410,7 +410,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
# Mary and Bob both have posts in misc, but they are the only ones.
authors = Author.joins(:similar_posts).where('posts.id' => posts(:misc_by_bob).id)
- assert_equal [authors(:mary), authors(:bob)], authors.uniq.sort_by(&:id)
+ assert_equal [authors(:mary), authors(:bob)], authors.distinct.sort_by(&:id)
# Check the polymorphism of taggings is being observed correctly (in both joins)
authors = Author.joins(:similar_posts).where('taggings.taggable_type' => 'FakeModel')
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 41529cd050..a06bacafca 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -237,6 +237,11 @@ class AssociationProxyTest < ActiveRecord::TestCase
assert david.projects.scope.is_a?(ActiveRecord::Relation)
assert_equal david.projects, david.projects.scope
end
+
+ test "proxy object is cached" do
+ david = developers(:david)
+ assert david.projects.equal?(david.projects)
+ end
end
class OverridingAssociationsTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index aa09df5743..960c27da3e 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -1105,7 +1105,7 @@ class BasicsTest < ActiveRecord::TestCase
res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
res7 = nil
assert_nothing_raised do
- res7 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count(distinct: true)
+ res7 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").distinct.count
end
assert_equal res6, res7
end
@@ -1358,9 +1358,9 @@ class BasicsTest < ActiveRecord::TestCase
def test_clear_cache!
# preheat cache
- c1 = Post.connection.schema_cache.columns['posts']
+ c1 = Post.connection.schema_cache.columns('posts')
ActiveRecord::Base.clear_cache!
- c2 = Post.connection.schema_cache.columns['posts']
+ c2 = Post.connection.schema_cache.columns('posts')
assert_not_equal c1, c2
end
@@ -1499,6 +1499,12 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal scope, Bird.uniq
end
+ def test_distinct_delegates_to_scoped
+ scope = stub
+ Bird.stubs(:all).returns(mock(:distinct => scope))
+ assert_equal scope, Bird.distinct
+ end
+
def test_table_name_with_2_abstract_subclasses
assert_equal "photos", Photo.table_name
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index be49e948fc..c645523905 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -305,8 +305,8 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_count_selected_field_with_include
- assert_equal 6, Account.includes(:firm).count(:distinct => true)
- assert_equal 4, Account.includes(:firm).select(:credit_limit).count(:distinct => true)
+ assert_equal 6, Account.includes(:firm).distinct.count
+ assert_equal 4, Account.includes(:firm).distinct.select(:credit_limit).count
end
def test_should_not_perform_joined_include_by_default
@@ -341,7 +341,18 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 5, Account.count(:firm_id)
end
- def test_count_with_uniq
+ def test_count_distinct_option_is_deprecated
+ assert_deprecated do
+ assert_equal 4, Account.select(:credit_limit).count(distinct: true)
+ end
+
+ assert_deprecated do
+ assert_equal 6, Account.select(:credit_limit).count(distinct: false)
+ end
+ end
+
+ def test_count_with_distinct
+ assert_equal 4, Account.select(:credit_limit).distinct.count
assert_equal 4, Account.select(:credit_limit).uniq.count
end
@@ -351,7 +362,7 @@ class CalculationsTest < ActiveRecord::TestCase
def test_should_count_field_in_joined_table
assert_equal 5, Account.joins(:firm).count('companies.id')
- assert_equal 4, Account.joins(:firm).count('companies.id', :distinct => true)
+ assert_equal 4, Account.joins(:firm).distinct.count('companies.id')
end
def test_should_count_field_in_joined_table_with_group_by
@@ -455,7 +466,7 @@ class CalculationsTest < ActiveRecord::TestCase
approved_topics_count = Topic.group(:approved).count(:author_name)[true]
assert_equal approved_topics_count, 3
# Count the number of distinct authors for approved Topics
- distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true]
+ distinct_authors_for_approved_count = Topic.group(:approved).distinct.count(:author_name)[true]
assert_equal distinct_authors_for_approved_count, 2
end
diff --git a/activerecord/test/cases/connection_adapters/schema_cache_test.rb b/activerecord/test/cases/connection_adapters/schema_cache_test.rb
index 541e983758..ecad7c942f 100644
--- a/activerecord/test/cases/connection_adapters/schema_cache_test.rb
+++ b/activerecord/test/cases/connection_adapters/schema_cache_test.rb
@@ -9,49 +9,46 @@ module ActiveRecord
end
def test_primary_key
- assert_equal 'id', @cache.primary_keys['posts']
+ assert_equal 'id', @cache.primary_keys('posts')
end
def test_primary_key_for_non_existent_table
- assert_nil @cache.primary_keys['omgponies']
+ assert_nil @cache.primary_keys('omgponies')
end
def test_caches_columns
- columns = @cache.columns['posts']
- assert_equal columns, @cache.columns['posts']
+ columns = @cache.columns('posts')
+ assert_equal columns, @cache.columns('posts')
end
def test_caches_columns_hash
- columns_hash = @cache.columns_hash['posts']
- assert_equal columns_hash, @cache.columns_hash['posts']
+ columns_hash = @cache.columns_hash('posts')
+ assert_equal columns_hash, @cache.columns_hash('posts')
end
def test_clearing
- @cache.columns['posts']
- @cache.columns_hash['posts']
- @cache.tables['posts']
- @cache.primary_keys['posts']
+ @cache.columns('posts')
+ @cache.columns_hash('posts')
+ @cache.tables('posts')
+ @cache.primary_keys('posts')
@cache.clear!
- assert_equal 0, @cache.columns.size
- assert_equal 0, @cache.columns_hash.size
- assert_equal 0, @cache.tables.size
- assert_equal 0, @cache.primary_keys.size
+ assert_equal 0, @cache.size
end
def test_dump_and_load
- @cache.columns['posts']
- @cache.columns_hash['posts']
- @cache.tables['posts']
- @cache.primary_keys['posts']
+ @cache.columns('posts')
+ @cache.columns_hash('posts')
+ @cache.tables('posts')
+ @cache.primary_keys('posts')
@cache = Marshal.load(Marshal.dump(@cache))
- assert_equal 12, @cache.columns['posts'].size
- assert_equal 12, @cache.columns_hash['posts'].size
- assert @cache.tables['posts']
- assert_equal 'id', @cache.primary_keys['posts']
+ assert_equal 12, @cache.columns('posts').size
+ assert_equal 12, @cache.columns_hash('posts').size
+ assert @cache.tables('posts')
+ assert_equal 'id', @cache.primary_keys('posts')
end
end
diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb
index fc46a249c8..7de2ceae88 100644
--- a/activerecord/test/cases/counter_cache_test.rb
+++ b/activerecord/test/cases/counter_cache_test.rb
@@ -131,4 +131,11 @@ class CounterCacheTest < ActiveRecord::TestCase
Subscriber.reset_counters(subscriber.id, 'books')
end
end
+
+ test "the passed symbol needs to be an association name" do
+ e = assert_raises(ArgumentError) do
+ Topic.reset_counters(@topic.id, :replies_count)
+ end
+ assert_equal "'Topic' has no association called 'replies_count'", e.message
+ end
end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index a9fa107749..e505fe9f18 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -82,7 +82,7 @@ class FinderTest < ActiveRecord::TestCase
# ensures +exists?+ runs valid SQL by excluding order value
def test_exists_with_order
- assert Topic.order(:id).uniq.exists?
+ assert Topic.order(:id).distinct.exists?
end
def test_exists_with_includes_limit_and_empty_result
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index fd0b05cb77..9ca980fdf6 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -278,5 +278,17 @@ module ActiveRecord
assert_equal [NullRelation], relation.extending_values
assert relation.is_a?(NullRelation)
end
+
+ test "distinct!" do
+ relation.distinct! :foo
+ assert_equal :foo, relation.distinct_value
+ assert_equal :foo, relation.uniq_value # deprecated access
+ end
+
+ test "uniq! was replaced by distinct!" do
+ relation.uniq! :foo
+ assert_equal :foo, relation.distinct_value
+ assert_equal :foo, relation.uniq_value # deprecated access
+ end
end
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 26cbb03892..9008c2785e 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -492,6 +492,7 @@ class RelationTest < ActiveRecord::TestCase
expected_taggings = taggings(:welcome_general, :thinking_general)
assert_no_queries do
+ assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id }
assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
end
@@ -789,11 +790,11 @@ class RelationTest < ActiveRecord::TestCase
def test_count_with_distinct
posts = Post.all
- assert_equal 3, posts.count(:comments_count, :distinct => true)
- assert_equal 11, posts.count(:comments_count, :distinct => false)
+ assert_equal 3, posts.distinct(true).count(:comments_count)
+ assert_equal 11, posts.distinct(false).count(:comments_count)
- assert_equal 3, posts.select(:comments_count).count(:distinct => true)
- assert_equal 11, posts.select(:comments_count).count(:distinct => false)
+ assert_equal 3, posts.distinct(true).select(:comments_count).count
+ assert_equal 11, posts.distinct(false).select(:comments_count).count
end
def test_count_explicit_columns
@@ -1223,6 +1224,16 @@ class RelationTest < ActiveRecord::TestCase
end
end
+ def test_turn_off_eager_loading_with_conditions_on_joins
+ original_value = ActiveRecord::Base.disable_implicit_join_references
+ ActiveRecord::Base.disable_implicit_join_references = true
+
+ scope = Topic.where(author_email_address: 'my.example@gmail.com').includes(:replies)
+ assert_not scope.eager_loading?
+ ensure
+ ActiveRecord::Base.disable_implicit_join_references = original_value
+ end
+
def test_ordering_with_extra_spaces
assert_equal authors(:david), Author.order('id DESC , name DESC').last
end
@@ -1269,7 +1280,7 @@ class RelationTest < ActiveRecord::TestCase
assert_equal posts(:welcome), comments(:greetings).post
end
- def test_uniq
+ def test_distinct
tag1 = Tag.create(:name => 'Foo')
tag2 = Tag.create(:name => 'Foo')
@@ -1277,11 +1288,14 @@ class RelationTest < ActiveRecord::TestCase
assert_equal ['Foo', 'Foo'], query.map(&:name)
assert_sql(/DISTINCT/) do
+ assert_equal ['Foo'], query.distinct.map(&:name)
assert_equal ['Foo'], query.uniq.map(&:name)
end
assert_sql(/DISTINCT/) do
+ assert_equal ['Foo'], query.distinct(true).map(&:name)
assert_equal ['Foo'], query.uniq(true).map(&:name)
end
+ assert_equal ['Foo', 'Foo'], query.distinct(true).distinct(false).map(&:name)
assert_equal ['Foo', 'Foo'], query.uniq(true).uniq(false).map(&:name)
end
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index 8423411474..a96899ae10 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -30,8 +30,8 @@ class Author < ActiveRecord::Base
has_many :comments_desc, -> { order('comments.id DESC') }, :through => :posts, :source => :comments
has_many :limited_comments, -> { limit(1) }, :through => :posts, :source => :comments
has_many :funky_comments, :through => :posts, :source => :comments
- has_many :ordered_uniq_comments, -> { uniq.order('comments.id') }, :through => :posts, :source => :comments
- has_many :ordered_uniq_comments_desc, -> { uniq.order('comments.id DESC') }, :through => :posts, :source => :comments
+ has_many :ordered_uniq_comments, -> { distinct.order('comments.id') }, :through => :posts, :source => :comments
+ has_many :ordered_uniq_comments_desc, -> { distinct.order('comments.id DESC') }, :through => :posts, :source => :comments
has_many :readonly_comments, -> { readonly }, :through => :posts, :source => :comments
has_many :special_posts
@@ -78,7 +78,7 @@ class Author < ActiveRecord::Base
has_many :categories_like_general, -> { where(:name => 'General') }, :through => :categorizations, :source => :category, :class_name => 'Category'
has_many :categorized_posts, :through => :categorizations, :source => :post
- has_many :unique_categorized_posts, -> { uniq }, :through => :categorizations, :source => :post
+ has_many :unique_categorized_posts, -> { distinct }, :through => :categorizations, :source => :post
has_many :nothings, :through => :kateggorisatons, :class_name => 'Category'
@@ -91,7 +91,7 @@ class Author < ActiveRecord::Base
has_many :post_categories, :through => :posts, :source => :categories
has_many :tagging_tags, :through => :taggings, :source => :tag
- has_many :similar_posts, -> { uniq }, :through => :tags, :source => :tagged_posts
+ has_many :similar_posts, -> { distinct }, :through => :tags, :source => :tagged_posts
has_many :distinct_tags, -> { select("DISTINCT tags.*").order("tags.name") }, :through => :posts, :source => :tags
has_many :tags_with_primary_key, :through => :posts
diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb
index ce81a37966..5458a28cc9 100644
--- a/activerecord/test/models/book.rb
+++ b/activerecord/test/models/book.rb
@@ -2,7 +2,7 @@ class Book < ActiveRecord::Base
has_many :authors
has_many :citations, :foreign_key => 'book1_id'
- has_many :references, -> { uniq }, :through => :citations, :source => :reference_of
+ has_many :references, -> { distinct }, :through => :citations, :source => :reference_of
has_many :subscriptions
has_many :subscribers, :through => :subscriptions
diff --git a/activerecord/test/models/liquid.rb b/activerecord/test/models/liquid.rb
index 6cfd443e75..69d4d7df1a 100644
--- a/activerecord/test/models/liquid.rb
+++ b/activerecord/test/models/liquid.rb
@@ -1,5 +1,4 @@
class Liquid < ActiveRecord::Base
self.table_name = :liquid
- has_many :molecules, -> { uniq }
+ has_many :molecules, -> { distinct }
end
-
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 90273adafc..f893754b9f 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -1,11 +1,11 @@
class Project < ActiveRecord::Base
- has_and_belongs_to_many :developers, -> { uniq.order 'developers.name desc, developers.id desc' }
+ has_and_belongs_to_many :developers, -> { distinct.order 'developers.name desc, developers.id desc' }
has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer"
- has_and_belongs_to_many :selected_developers, -> { uniq.select "developers.*" }, :class_name => "Developer"
+ has_and_belongs_to_many :selected_developers, -> { distinct.select "developers.*" }, :class_name => "Developer"
has_and_belongs_to_many :non_unique_developers, -> { order 'developers.name desc, developers.id desc' }, :class_name => 'Developer'
has_and_belongs_to_many :limited_developers, -> { limit 1 }, :class_name => "Developer"
- has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").uniq }, :class_name => "Developer"
- has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(:name => 'David').uniq }, :class_name => "Developer"
+ has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").distinct }, :class_name => "Developer"
+ has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(:name => 'David').distinct }, :class_name => "Developer"
has_and_belongs_to_many :salaried_developers, -> { where "salary > 0" }, :class_name => "Developer"
ActiveSupport::Deprecation.silence do
diff --git a/activesupport/lib/active_support/tagged_logging.rb b/activesupport/lib/active_support/tagged_logging.rb
index 18bc919734..09bfc95231 100644
--- a/activesupport/lib/active_support/tagged_logging.rb
+++ b/activesupport/lib/active_support/tagged_logging.rb
@@ -54,6 +54,14 @@ module ActiveSupport
end
end
+ def self.create(f, formatter, level)
+ logger = ActiveSupport::Logger.new f
+ logger.formatter = formatter
+ logger = new(logger)
+ logger.level = ActiveSupport::Logger.const_get(level.to_s.upcase)
+ logger
+ end
+
def self.new(logger)
# Ensure we set a default formatter so we aren't extending nil!
logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new
diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb
index 27f629474e..0f5b2cba8f 100644
--- a/activesupport/test/tagged_logging_test.rb
+++ b/activesupport/test/tagged_logging_test.rb
@@ -22,6 +22,17 @@ class TaggedLoggingTest < ActiveSupport::TestCase
assert logger.formatter.respond_to?(:tagged)
end
+ test 'creates a tagged logger with the appropriate level and formatter' do
+ stringio = StringIO.new
+ logger = ActiveSupport::TaggedLogging.create(stringio, ActiveSupport::Logger::SimpleFormatter.new, :debug)
+ logger.debug("foo")
+
+ assert_not_nil logger.formatter
+ assert logger.formatter.respond_to?(:tagged)
+ assert_equal 0, logger.level
+ assert stringio.string.include?("foo")
+ end
+
test "tagged once" do
@logger.tagged("BCX") { @logger.info "Funky time" }
assert_equal "[BCX] Funky time\n", @output.string
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 4a4f814917..7355f6816c 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -76,6 +76,7 @@ The methods are:
* `reorder`
* `reverse_order`
* `select`
+* `distinct`
* `uniq`
* `where`
@@ -580,10 +581,10 @@ ActiveModel::MissingAttributeError: missing attribute: <attribute>
Where `<attribute>` is the attribute you asked for. The `id` method will not raise the `ActiveRecord::MissingAttributeError`, so just be careful when working with associations because they need the `id` method to function properly.
-If you would like to only grab a single record per unique value in a certain field, you can use `uniq`:
+If you would like to only grab a single record per unique value in a certain field, you can use `distinct`:
```ruby
-Client.select(:name).uniq
+Client.select(:name).distinct
```
This would generate SQL like:
@@ -595,10 +596,10 @@ SELECT DISTINCT name FROM clients
You can also remove the uniqueness constraint:
```ruby
-query = Client.select(:name).uniq
+query = Client.select(:name).distinct
# => Returns unique names
-query.uniq(false)
+query.distinct(false)
# => Returns all names, even if there are duplicates
```
@@ -1438,7 +1439,7 @@ Client.where(active: true).pluck(:id)
# SELECT id FROM clients WHERE active = 1
# => [1, 2, 3]
-Client.uniq.pluck(:role)
+Client.distinct.pluck(:role)
# SELECT DISTINCT role FROM clients
# => ['admin', 'member', 'guest']
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index a1d7e955c8..a1864c123e 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -103,7 +103,7 @@ To verify that you have everything installed correctly, you should be able to ru
$ rails --version
```
-If it says something like "Rails 3.2.9", you are ready to continue.
+If it says something like "Rails 4.0.0", you are ready to continue.
### Creating the Blog Application
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 40bf2603c4..1937cbf17a 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -501,6 +501,21 @@ You also have access to three instance variables in your functional tests:
* `@request` - The request
* `@response` - The response
+### Setting Headers and CGI variables
+
+Headers and cgi variables can be set directly on the `@request`
+instance variable:
+
+```ruby
+# setting a HTTP Header
+@request.headers["Accepts"] = "text/plain, text/html"
+get :index # simulate the request with custom header
+
+# setting a CGI variable
+@request.headers["HTTP_REFERER"] = "http://example.com/home"
+post :create # simulate the request with custom env variable
+```
+
### Testing Templates and Layouts
If you want to make sure that the response rendered the correct template and layout, you can use the `assert_template`
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 60a823de15..9e9d7e9009 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,5 +1,9 @@
## Rails 4.0.0 (unreleased) ##
+* New rails apps log to STDOUT by default
+
+ *Terence Lee*
+
* Add support for generate scaffold password:digest
* adds password_digest attribute to the migration
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 62d57c0cc6..2a845bca17 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -39,11 +39,7 @@ INFO
f.binmode
f.sync = config.autoflush_log # if true make sure every write flushes
- logger = ActiveSupport::Logger.new f
- logger.formatter = config.log_formatter
- logger = ActiveSupport::TaggedLogging.new(logger)
- logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
- logger
+ logger = ActiveSupport::TaggedLogging.create(f, config.log_formatter, config.log_level)
rescue StandardError
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
logger.level = ActiveSupport::Logger::WARN
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index daf399a538..2df2fa9a6a 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -32,5 +32,7 @@ module <%= app_const_base %>
# Disable the asset pipeline.
config.assets.enabled = false
<% end -%>
+
+ config.logger = ActiveSupport::TaggedLogging.create(STDOUT, config.log_formatter, config.log_level)
end
end
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index de44bf9e4d..3c247f32c0 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -79,7 +79,6 @@ namespace :test do
# Display deprecation message
task :deprecated do
- task_name = ARGV.first
ActiveSupport::Deprecation.warn "`rake #{ARGV.first}` is deprecated with no replacement."
end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 7b45623f6c..40000b0ce6 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -670,5 +670,26 @@ module ApplicationTests
end
end
end
+
+ test "set logger to STDOUT by default" do
+ stdout = capture(:stdout) do
+ app = build_app
+
+ controller :omg, <<-RUBY
+ class OmgController < ApplicationController
+ def index
+ Rails.logger.info "HI MOM"
+ render text: "omg"
+ end
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ get "/omg/index"
+ end
+
+ assert stdout.include?("HI MOM"), "STDOUT does not include 'HI MOM', #{stdout}"
+ end
end
end