diff options
author | Dmitry Polushkin <dmitry.polushkin@gmail.com> | 2011-12-31 01:10:42 +0000 |
---|---|---|
committer | Dmitry Polushkin <dmitry.polushkin@gmail.com> | 2011-12-31 01:10:42 +0000 |
commit | 04bc40ff501b1bf81bec7ce3937cb06c896ffc69 (patch) | |
tree | 88a33663195900df8a7307aefa2c9aaa561c3973 /activerecord | |
parent | 84eece0a823e9c601ea99a8709f24605a19bcbfd (diff) | |
parent | ed17983ec56dec689a0311c7f8fcbeba9874e5a4 (diff) | |
download | rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.tar.gz rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.tar.bz2 rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.zip |
Merge branch 'master' of git://github.com/rails/rails
Diffstat (limited to 'activerecord')
225 files changed, 13689 insertions, 10667 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG deleted file mode 100644 index f974b5d237..0000000000 --- a/activerecord/CHANGELOG +++ /dev/null @@ -1,6538 +0,0 @@ -*Rails 3.1.1 (unreleased)* - -* Add deprecation for the preload_associations method. Fixes #3022. - - [Jon Leighton] - -* Don't require a DB connection when loading a model that uses set_primary_key. GH #2807. - - [Jon Leighton] - -* Fix using select() with a habtm association, e.g. Person.friends.select(:name). GH #3030 and - #2923. - - [Hendy Tanata] - -* Fix belongs_to polymorphic with custom primary key on target. GH #3104. - - [Jon Leighton] - -* CollectionProxy#replace should change the DB records rather than just mutating the array. - Fixes #3020. - - [Jon Leighton] - -* LRU cache in mysql and sqlite are now per-process caches. - - * lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache - keys are per process id. - * lib/active_record/connection_adapters/sqlite_adapter.rb: ditto - -* Add first_or_create, first_or_create!, first_or_initialize methods to Active Record. This is a - better approach over the old find_or_create_by dynamic methods because it's clearer which - arguments are used to find the record and which are used to create it: - - User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson") - - [Andrés Mejía] - -* Support bulk change_table in mysql2 adapter, as well as the mysql one. [Jon Leighton] - -* If multiple parameters are sent representing a date, and some are blank, the -resulting object is nil. In previous releases those values defaulted to 1. This -only affects existing but blank parameters, missing ones still raise an error. -[Akira Matsuda] - -* ActiveRecord::Base.establish_connection now takes a string that contains -a URI that specifies the connection configuration. For example: - - ActiveRecord::Base.establish_connection 'postgres://localhost/foo' - -* Active Record's dynamic finder will now raise the error if you passing in less number of arguments than what you call in method signature. - - So if you were doing this and expecting the second argument to be nil: - - User.find_by_username_and_group("sikachu") - - You'll now get `ArgumentError: wrong number of arguments (1 for 2).` You'll then have to do this: - - User.find_by_username_and_group("sikachu", nil) - - [Prem Sichanugrist] - -*Rails 3.1.0 (August 30, 2011)* - -* Add a proxy_association method to association proxies, which can be called by association - extensions to access information about the association. This replaces proxy_owner etc with - proxy_association.owner. - - [Jon Leighton] - -* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature. - - Before: def build_association(*options) - After: def build_association(*options, &block) - - Users who are redefining this method to extend functionality should ensure that the block is - passed through to ActiveRecord::Base#new. - - This change is necessary to fix https://github.com/rails/rails/issues/1842. - - [Jon Leighton] - -* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model: - - class User < ActiveRecord::Base - self.pluralize_table_names = false - end - - Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. [Guillermo Iguaran] - -* Add block setting of attributes to singular associations: - - class User < ActiveRecord::Base - has_one :account - end - - user.build_account{ |a| a.credit_limit => 100.0 } - - The block is called after the instance has been initialized. [Andrew White] - -* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. [Prem Sichanugrist] - -* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0 - -* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you - to specify which role to consider when assigning attributes. This is built on top of ActiveModel's - new mass assignment capabilities: - - class Post < ActiveRecord::Base - attr_accessible :title - attr_accessible :title, :published_at, :as => :admin - end - - Post.new(params[:post], :as => :admin) - - assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated. - - Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly. - - [Josh Kalderimis] - -* default_scope can take a block, lambda, or any other object which responds to `call` for lazy - evaluation: - - default_scope { ... } - default_scope lambda { ... } - default_scope method(:foo) - - This feature was originally implemented by Tim Morgan, but was then removed in favour of - defining a 'default_scope' class method, but has now been added back in by Jon Leighton. - The relevant lighthouse ticket is #1812. - -* Default scopes are now evaluated at the latest possible moment, to avoid problems where - scopes would be created which would implicitly contain the default scope, which would then - be impossible to get rid of via Model.unscoped. - - Note that this means that if you are inspecting the internal structure of an - ActiveRecord::Relation, it will *not* contain the default scope, though the resulting - query will do. You can get a relation containing the default scope by calling - ActiveRecord#with_default_scope, though this is not part of the public API. - - [Jon Leighton] - -* If you wish to merge default scopes in special ways, it is recommended to define your default - scope as a class method and use the standard techniques for sharing code (inheritance, mixins, - etc.): - - class Post < ActiveRecord::Base - def self.default_scope - where(:published => true).where(:hidden => false) - end - end - - [Jon Leighton] - -* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher. - -* ConnectionManagement middleware is changed to clean up the connection pool - after the rack body has been flushed. - -* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks. - It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of - the updated_at column. It should not be called on new records. - Example: - - User.first.update_column(:name, "sebastian") # => true - - [Sebastian Martinez] - -* Associations with a :through option can now use *any* association as the - through or source association, including other associations which have a - :through option and has_and_belongs_to_many associations - - [Jon Leighton] - -* The configuration for the current database connection is now accessible via - ActiveRecord::Base.connection_config. [fxn] - -* limits and offsets are removed from COUNT queries unless both are supplied. - For example: - - People.limit(1).count # => 'SELECT COUNT(*) FROM people' - People.offset(1).count # => 'SELECT COUNT(*) FROM people' - People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1' - - [lighthouse #6262] - -* ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class - (and subclasses) which are responsible for operating on associations, and then a separate, - thin wrapper called CollectionProxy, which proxies collection associations. - - This prevents namespace pollution, separates concerns, and will allow further refactorings. - - Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return - the associated record or nil. This means that you should not use undocumented methods such - as bob.mother.create - use bob.create_mother instead. - - [Jon Leighton] - -* Make has_many :through associations work correctly when you build a record and then save it. This - requires you to set the :inverse_of option on the source reflection on the join model, like so: - - class Post < ActiveRecord::Base - has_many :taggings - has_many :tags, :through => :taggings - end - - class Tagging < ActiveRecord::Base - belongs_to :post - belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set! - end - - class Tag < ActiveRecord::Base - has_many :taggings - has_many :posts, :through => :taggings - end - - post = Post.first - tag = post.tags.build :name => "ruby" - tag.save # will save a Taggable linking to the post - - [Jon Leighton] - -* Support the :dependent option on has_many :through associations. For historical and practical - reasons, :delete_all is the default deletion strategy employed by association.delete(*records), - despite the fact that the default strategy is :nullify for regular has_many. Also, this only - works at all if the source reflection is a belongs_to. For other situations, you should directly - modify the through association. - - [Jon Leighton] - -* Changed the behaviour of association.destroy for has_and_belongs_to_many and has_many :through. - From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', - not (necessarily) 'get rid of the associated records'. - - Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It - would not delete any records in the join table. Now, it deletes the records in the join table. - - Previously, has_many_through.destroy(*records) would destroy the records themselves, and the - records in the join table. [Note: This has not always been the case; previous version of Rails - only deleted the records themselves.] Now, it destroys only the records in the join table. - - Note that this change is backwards-incompatible to an extent, but there is unfortunately no - way to 'deprecate' it before changing it. The change is being made in order to have - consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. - - If you wish to destroy the records themselves, you can do records.association.each(&:destroy) - - [Jon Leighton] - -* Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. [Pratik Naik] - - Example: - - change_table(:users, :bulk => true) do |t| - t.string :company_name - t.change :birthdate, :datetime - end - - This will now result in: - - ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL - -* Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been - documented as deprecated behaviour since April 2006. Please use has_many :through instead. - [Jon Leighton] - -* Added a create_association! method for has_one and belongs_to associations. [Jon Leighton] - -* Migration files generated from model and constructive migration generators - (for example, add_name_to_users) use the reversible migration's `change` - method instead of the ordinary `up` and `down` methods. [Prem Sichanugrist] - -* Removed support for interpolating string SQL conditions on associations. Instead, you should - use a proc, like so: - - Before: - - has_many :things, :conditions => 'foo = #{bar}' - - After: - - has_many :things, :conditions => proc { "foo = #{bar}" } - - Inside the proc, 'self' is the object which is the owner of the association, unless you are - eager loading the association, in which case 'self' is the class which the association is within. - - You can have any "normal" conditions inside the proc, so the following will work too: - - has_many :things, :conditions => proc { ["foo = ?", bar] } - - Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call - 'record' to get the record being inserted or deleted. This is now passed as an argument to - the proc. - -* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example: - - # Schema: User(name:string, password_digest:string, password_salt:string) - class User < ActiveRecord::Base - has_secure_password - end - - user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch") - user.save # => false, password required - user.password = "mUc3m00RsqyRe" - user.save # => false, confirmation doesn't match - user.password_confirmation = "mUc3m00RsqyRe" - user.save # => true - user.authenticate("notright") # => false - user.authenticate("mUc3m00RsqyRe") # => user - User.find_by_name("david").try(:authenticate, "notright") # => nil - User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user - - -* When a model is generated add_index is added by default for belongs_to or references columns - - rails g model post user:belongs_to will generate the following: - - class CreatePosts < ActiveRecord::Migration - def up - create_table :posts do |t| - t.belongs_to :user - t.timestamps - end - - add_index :posts, :user_id - end - - def down - drop_table :posts - end - end - - [Santiago Pastorino] - -* Setting the id of a belongs_to object will update the reference to the -object. [#2989 state:resolved] - -* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed -to closer match normal Ruby dup and clone semantics. - -* Calling ActiveRecord::Base#clone will result in a shallow copy of the record, -including copying the frozen state. No callbacks will be called. - -* Calling ActiveRecord::Base#dup will duplicate the record, including calling -after initialize hooks. Frozen state will not be copied, and all associations -will be cleared. A duped record will return true for new_record?, have a nil -id field, and is saveable. - -* Migrations can be defined as reversible, meaning that the migration system -will figure out how to reverse your migration. To use reversible migrations, -just define the "change" method. For example: - - class MyMigration < ActiveRecord::Migration - def change - create_table(:horses) do - t.column :content, :text - t.column :remind_at, :datetime - end - end - end - -Some things cannot be automatically reversed for you. If you know how to -reverse those things, you should define 'up' and 'down' in your migration. If -you define something in `change` that cannot be reversed, an -IrreversibleMigration exception will be raised when going down. - -* Migrations should use instance methods rather than class methods: - class FooMigration < ActiveRecord::Migration - def up - ... - end - end - - [Aaron Patterson] - -* has_one maintains the association with separate after_create/after_update instead - of a single after_save. [fxn] - -* The following code: - - Model.limit(10).scoping { Model.count } - - now generates the following SQL: - - SELECT COUNT(*) FROM models LIMIT 10 - - This may not return what you want. Instead, you may with to do something - like this: - - Model.limit(10).scoping { Model.all.size } - - [Aaron Patterson] - - -*Rails 3.0.7 (April 18, 2011)* - -* Destroying records via nested attributes works independent of reject_if LH #6006 [Durran Jordan] - -* Delegate any? and many? to Model.scoped for consistency [Andrew White] - -* Quote the ORDER BY clause in batched finds - fixes #6620 [Andrew White] - -* Change exists? so records are not instantiated - fixes #6127. This prevents after_find - and after_initialize callbacks being triggered when checking for record existence. - [Andrew White] - -* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we - cache type-casted values when the column returned from the db contains non-standard chars. - [Jon Leighton] - -* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8 - related to read_attribute method [Stian Grytøyr] - - -*Rails 3.0.6 (April 5, 2011)* - -* Un-deprecate reorder method [Sebastian Martinez] - -* Extensions are applied when calling +except+ or +only+ on relations. - Thanks to Iain Hecker. - -* Schemas set in set_table_name are respected by the mysql adapter. LH #5322 - -* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded. - LH #5829 - -* Reapply extensions when using except and only. Thanks Iain Hecker. - -* Binary data is escaped when being inserted to SQLite3 Databases. Thanks - Naruse! - - -*Rails 3.0.5 (February 26, 2011)* - -* Model.where(:column => 1).where(:column => 2) will always produce an AND -query. - - [Aaron Patterson] - -* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'. - - Instead, you should use a proc, like so: - - Before: - - has_many :things, :conditions => 'foo = #{bar}' - - After: - - has_many :things, :conditions => proc { "foo = #{bar}" } - - Inside the proc, 'self' is the object which is the owner of the association, unless you are - eager loading the association, in which case 'self' is the class which the association is within. - - You can have any "normal" conditions inside the proc, so the following will work too: - - has_many :things, :conditions => proc { ["foo = ?", bar] } - - Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call - 'record' to get the record being inserted or deleted. This is now passed as an argument to - the proc. - - [Jon Leighton] - - -*Rails 3.0.4 (February 8, 2011)* - -* Added deprecation warning for has_and_belongs_to_many associations where the join table has - additional attributes other than the keys. Access to these attributes is removed in 3.1. - Please use has_many :through instead. [Jon Leighton] - - -*Rails 3.0.3 (November 16, 2010)* - -* Support find by class like this: Post.where(:name => Post) - - -*Rails 3.0.2 (November 15, 2010)* - -* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) [Aaron Patterson] - -* reorder is deprecated in favor of except(:order).order(...) [Santiago Pastorino] - -* except is now AR public API - - Model.order('name').except(:order).order('salary') - - generates: - - SELECT * FROM models ORDER BY salary - - [Santiago Pastorino] - -* The following code: - - Model.limit(10).scoping { Model.count } - - now generates the following SQL: - - SELECT COUNT(*) FROM models LIMIT 10 - - This may not return what you want. Instead, you may with to do something - like this: - - Model.limit(10).scoping { Model.all.size } - - [Aaron Patterson] - - -*Rails 3.0.1 (October 15, 2010)* - -* Introduce a fix for CVE-2010-3993 - - -*Rails 3.0.0 (August 29, 2010)* - -* Changed update_attribute to not run callbacks and update the record directly in the database [Neeraj Singh] - -* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope [José Valim] - -* New rake task, db:migrate:status, displays status of migrations #4947 [Kevin Skoglund] - -* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten [Santiago Pastorino] - -* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 [Aaron Patterson] - -* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 [Andrew Bloomgarden, Andrew White] - -* Add index length support for MySQL. #1852 [Emili Parreno, Pratik Naik] - - Example: - - add_index(:accounts, :name, :name => 'by_name', :length => 10) - => CREATE INDEX by_name ON accounts(name(10)) - - add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15}) - => CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) - -* find_or_create_by_attr(value, ...) works when attr is protected. #4457 [Santiago Pastorino, Marc-André Lafortune] - -* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 [Brian Durand] - -* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). [José Valim] - -* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 [Curtis Hawthorne] - -* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. [Jeremy Kemper] - -* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 [Mislav Marohnić] - -* Add Relation extensions. [Pratik Naik] - - users = User.where(:admin => true).extending(User::AdminPowers) - - latest_users = User.order('created_at DESC') do - def posts_count - Post.count(:user_id => to_a.map(&:id)) - end - end - -* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 [Andrew White] - -* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development [DHH] - -* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 [Jack Christensen] - -* Allow relations to be used as scope. - - class Item - scope :red, where(:colour => 'red') - end - - Item.red.limit(10) # Ten red items - -* Rename named_scope to scope. [Pratik Naik] - -* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default [DHH] - -* Add Relation#except. [Pratik Naik] - - one_red_item = Item.where(:colour => 'red').limit(1) - all_items = one_red_item.except(:where, :limit) - -* Add Relation#delete_all. [Pratik Naik] - - Item.where(:colour => 'red').delete_all - -* Add Model.having and Relation#having. [Pratik Naik] - - Developer.group("salary").having("sum(salary) > 10000").select("salary") - -* Add Relation#count. [Pratik Naik] - - legends = People.where("age > 100") - legends.count - legends.count(:age, :distinct => true) - legends.select('id').count - -* Add Model.readonly and association_collection#readonly finder method. [Pratik Naik] - - Post.readonly.to_a # Load all posts in readonly mode - @user.items.readonly(false).to_a # Load all the user items in writable mode - -* Add .lock finder method [Pratik Naik] - - User.lock.where(:name => 'lifo').to_a - - old_items = Item.where("age > 100") - old_items.lock.each {|i| .. } - -* Add Model.from and association_collection#from finder methods [Pratik Naik] - - user = User.scoped - user.select('*').from('users, items') - -* Add relation.destroy_all [Pratik Naik] - - old_items = Item.where("age > 100") - old_items.destroy_all - -* Add relation.exists? [Pratik Naik] - - red_items = Item.where(:colours => 'red') - red_items.exists? - red_items.exists?(1) - -* Add find(ids) to relations. [Pratik Naik] - - old_users = User.order("age DESC") - old_users.find(1) - old_users.find(1, 2, 3) - -* Add new finder methods to association collection. [Pratik Naik] - - class User < ActiveRecord::Base - has_many :items - end - - user = User.first - user.items.where(:items => {:colour => 'red'}) - user.items.select('items.id') - -* Add relation.reload to force reloading the records. [Pratik Naik] - - topics = Topic.scoped - topics.to_a # force load - topics.first # returns a cached record - topics.reload - topics.first # Fetches a new record from the database - -* Rename Model.conditions and relation.conditions to .where. [Pratik Naik] - - Before : - User.conditions(:name => 'lifo') - User.select('id').conditions(["age > ?", 21]) - - Now : - User.where(:name => 'lifo') - User.select('id').where(["age > ?", 21]) - -* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. [Pratik Naik] - - Examples : - - posts = Post.select('id).order('name') # Returns a lazy relation - posts.each {|p| puts p.id } # Fires "select id from posts order by name" - -* Model.scoped now returns a relation if invoked without any arguments. [Pratik Naik] - - Example : - - posts = Post.scoped - posts.size # Fires "select count(*) from posts" and returns the count - posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects - -* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 [Murray Steele] - - # post.comments sets each comment's post without needing to :include - class Post < ActiveRecord::Base - has_many :comments, :inverse_of => :post - end - -* MySQL: add_ and change_column support positioning. #3286 [Ben Marini] - -* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 [Mike Breen, Gabe da Silveira] - -* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git [Pratik Naik] - -* PostgreSQL: XML datatype support. #1874 [Leonardo Borges] - -* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 [Geoff Buesing] - -* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 [Paul Hinze, Jeremy Kemper] - -* Added :primary_key option to belongs_to associations. #765 [Szymon Nowak, Philip Hallstrom, Noel Rocha] - # employees.company_name references companies.name - Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name' - -* Implement #many? for NamedScope and AssociationCollection using #size. #1500 [Chris Kampmeier] - -* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed [DHH] - -* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time [DHH] - - -*2.3.2 [Final] (March 15, 2009)* - -* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing [DHH/Jamis Buck] - -* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 [Scott Taylor] - -* Add Support for updating deeply nested models from a single form. #1202 [Eloy Duran] - - class Book < ActiveRecord::Base - has_one :author - has_many :pages - - accepts_nested_attributes_for :author, :pages - end - -* Make after_save callbacks fire only if the record was successfully saved. #1735 [Michael Lovitt] - - Previously the callbacks would fire if a before_save cancelled saving. - -* Support nested transactions using database savepoints. #383 [Jonathan Viney, Hongli Lai] - -* Added dynamic scopes ala dynamic finders #1648 [Yaroslav Markin] - -* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 [Yaroslav Markin] - -* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 [Akira Matsuda] - -* Add :having as a key to find and the relevant associations. [Emilio Tagua] - -* Added default_scope to Base #1381 [Paweł Kondzior]. Example: - - class Person < ActiveRecord::Base - default_scope :order => 'last_name, first_name' - end - - class Company < ActiveRecord::Base - has_many :people - end - - Person.all # => Person.find(:all, :order => 'last_name, first_name') - Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 }) - - -*2.2.1 [RC2] (November 14th, 2008)* - -* Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster] - -* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 [Andreas Korth] - - -*2.2.0 [RC1] (October 24th, 2008)* - -* Skip collection ids reader optimization if using :finder_sql [Jeremy Kemper] - -* Add Model#delete instance method, similar to Model.delete class method. #1086 [Hongli Lai (Phusion)] - -* MySQL: cope with quirky default values for not-null text columns. #1043 [Frederick Cheung] - -* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] [Geoff Buesing] - -* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] [Emilio Tagua] - -* Added find_last_by dynamic finder #762 [Emilio Tagua] - -* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 [Hongli Lai (Phusion)] - -* Changed benchmarks to be reported in milliseconds [David Heinemeier Hansson] - -* Connection pooling. #936 [Nick Sieger] - -* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 [Andrew White] - -* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 [Xavier Noria] - -* Transactional migrations for databases which support them. #834 [divoxx, Adam Wiggins, Tarmo Tänav] - -* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. [Andrew Stone, Nik Wakelin] - -* change_column_default preserves the not-null constraint. #617 [Tarmo Tänav] - -* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) [#334] - -* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example : - - # Ensure essay contains at least 100 words. - validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) } - -* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example: - - User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } } - Item.first :conditions => { :items => { :color => 'red' } } - -* Always treat integer :limit as byte length. #420 [Tarmo Tänav] - -* Partial updates don't update lock_version if nothing changed. #426 [Daniel Morrison] - -* Fix column collision with named_scope and :joins. #46 [Duncan Beevers, Mark Catley] - -* db:migrate:down and :up update schema_migrations. #369 [Michael Raidel, RaceCondition] - -* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. [Tarmo Tänav] - -* MySQL: rename_column preserves column defaults. #466 [Diego Algorta] - -* Add :from option to calculations. #397 [Ben Munat] - -* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. [Jan De Poorter] - -* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. [Jeremy Kemper] - -* Added SQL escaping for :limit and :offset in MySQL [Jonathan Wiess] - - -*2.1.0 (May 31st, 2008)* - -* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. [Rick Olson] - -* Add first/last methods to associations/named_scope. Resolved #226. [Ryan Bates] - -* Added SQL escaping for :limit and :offset #288 [Aaron Bedra, Steven Bristol, Jonathan Wiess] - -* Added first/last methods to associations/named_scope. Resolved #226. [Ryan Bates] - -* Ensure hm:t preloading honours reflection options. Resolves #137. [Frederick Cheung] - -* Added protection against duplicate migration names (Aslak Hellesøy) [#112] - -* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true [Geoff Buesing] - -* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. [Scott Fleckenstein, Geoff Buesing] - -* Added change_table for migrations (Jeff Dean) [#71]. Example: - - change_table :videos do |t| - t.timestamps # adds created_at, updated_at - t.belongs_to :goat # adds goat_id integer - t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit - t.remove :name, :email # removes the name and email columns - end - -* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) [#85] - -* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) [#39] - -* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) [#67] - -* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] [#26] - -* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL [David Heinemeier Hansson] - -* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. [Rick Olson] - -* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 [Jordi Bunster] - -* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 [Kamal Fariz Mahyuddin] - -* Ensure that respond_to? considers dynamic finder methods. Closes #11538. [James Mead] - -* Ensure that save on parent object fails for invalid has_one association. Closes #10518. [Pratik Naik] - -* Remove duplicate code from associations. [Pratik Naik] - -* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 [Ruy Asan] - -* Ensure HABTM#create and HABTM#build do not load entire association. [Pratik Naik] - -* Improve documentation. [Xavier Noria, Jack Danger Canty, leethal] - -* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} [Rick Olson] - - Post.find(1).to_json # => {"title": ...} - config.active_record.include_root_in_json = true - Post.find(1).to_json # => {"post": {"title": ...}} - -* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). [stopdropandrew] - -* PostgreSQL: create_ and drop_database support. #9042 [ez, pedz, Nick Sieger] - -* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. [Nik Wakelin, cavalle] - -* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. [Jeremy Kemper] - -* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled [Geoff Buesing] - -* Fixed that validates_size_of :within works in associations #11295, #10019 [cavalle] - -* Track changes to unsaved attributes. [Jeremy Kemper] - -* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 [John Barnette] - -* Fixed that has_many :through would ignore the hash conditions #11447 [Emilio Tagua] - -* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 [cavalle] - -* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 [cavalle] - -* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 [Jack Danger Canty] - -* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert] - -* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 [Emilio Tagua] - -* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 [nkallen, Chris O'Sullivan] - -* Merge the has_finder gem, renamed as 'named_scope'. #11404 [nkallen] - - class Article < ActiveRecord::Base - named_scope :published, :conditions => {:published => true} - named_scope :popular, :conditions => ... - end - - Article.published.paginate(:page => 1) - Article.published.popular.count - Article.popular.find(:first) - Article.popular.find(:all, :conditions => {...}) - - See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries - -* Add has_one :through support. #4756 [Chris O'Sullivan] - -* Migrations: create_table supports primary_key_prefix_type. #10314 [student, Chris O'Sullivan] - -* Added logging for dependency load errors with fixtures #11056 [stuthulhu] - -* Time zone aware attributes use Time#in_time_zone [Geoff Buesing] - -* Fixed that scoped joins would not always be respected #6821 [Theory/Jack Danger Canty] - -* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 [cavalle] - -* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 [jramirez] - -* Added ActiveRecord::Base.find(:last) #11338 [Emilio Tagua] - -* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition [Geoff Buesing] - -* Add :readonly option to HasManyThrough associations. #11156 [Emilio Tagua] - -* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 [dasil003] - -* Perf fix: Avoid the use of named block arguments. Closes #11109 [adymo] - -* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 [jdavis] - -* Ensure association preloading doesn't break when an association returns nil. ##11145 [GMFlash] - -* Make dynamic finders respect the :include on HasManyThrough associations. #10998. [cpytel] - -* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability [Geoff Buesing] - -* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback [Geoff Buesing] - -* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 [adymo] - -* Optimise the BigDecimal conversion code. #11110 [adymo] - -* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 [Emilio Tagua] - -* Multiparameter attributes for time columns fail over to DateTime when out of range of Time [Geoff Buesing] - -* Base#instantiate_time_object uses Time.zone.local() [Geoff Buesing] - -* Add timezone-aware attribute readers and writers. #10982 [Geoff Buesing] - -* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 [Rick Olson] - -* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 [Xavier Noria] - -* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 [mdeiters] - -* belongs_to supports :dependent => :destroy and :delete. #10592 [Jonathan Viney] - -* Introduce preload query strategy for eager :includes. #9640 [Frederick Cheung, Aliaksey Kandratsenka, codafoo] - -* Support aggregations in finder conditions. #10572 [Ryan Kinderman] - -* Organize and clean up the Active Record test suite. #10742 [John Barnette] - -* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 [john.andrews] - -* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 [railsjitsu] - -* Fixtures: removed support for the ancient pre-YAML file format. #10736 [John Barnette] - -* More thoroughly quote table names. #10698 [dimdenis, lotswholetime, Jeremy Kemper] - -* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 [Brendan Ribera] - -* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries [David Heinemeier Hansson] - -* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. [JEG2] - -* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 [Sam] - -* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 [jamesh, Frederick Cheung, protocool] - -* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 [stopdropandrew, canadaduane] - -* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 [Jonathan Viney] - -* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 [Brandon Keepers] - -* Ruby 1.9 compatibility. #10655 [Jeremy Kemper, Dirkjan Bussink] - - -*2.0.2* (December 16th, 2007) - -* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 [Rick Olson] - -* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 [brynary] - -* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 [Josh Susser] - -* Ensure that the :uniq option for has_many :through associations retains the order. #10463 [remvee] - -* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 [Michael Klishin] - -* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 [Michael Klishin] - - -*2.0.1* (December 7th, 2007) - -* Removed query cache rescue as it could cause code to be run twice (closes #10408) [David Heinemeier Hansson] - - -*2.0.0* (December 6th, 2007) - -* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ [Geoff Buesing] - -* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) [David Heinemeier Hansson] - -* Fixed that the truncation of strings longer than 50 chars should use inspect -so newlines etc are escaped #10385 [Norbert Crombach] - -* Fixed that habtm associations should be able to set :select as part of their definition and have that honored [David Heinemeier Hansson] - -* Document how the :include option can be used in Calculations::calculate. Closes #7446 [adamwiggins, ultimoamore] - -* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 [johnjosephbachir] - -* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 [adamwiggins, mikong] - -* More complete documentation for find_by_sql. Closes #7912 [fearoffish] - -* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example: - - render :partial => @client.becomes(Company) # renders companies/company instead of clients/client - -* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 [Cheah Chu Yeow] - -* Fix documentation typo introduced in [8250]. Closes #10339 [Henrik N] - -* Foxy fixtures: support single-table inheritance. #10234 [tom] - -* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 [lotswholetime] - -* Make the record_timestamps class-inheritable so it can be set per model. #10004 [tmacedo] - -* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 [ambethia] - -* DateTimes use Ruby's default calendar reform setting. #10201 [Geoff Buesing] - -* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 [Patrick Joyce, Rick Olson, Jack Danger Canty] - -* Add 'foxy' support for fixtures of polymorphic associations. #10183 [John Barnette, David Lowenfels] - -* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 [devrieda, Mike Naberezny] - -* attr_readonly behaves well with optimistic locking. #10188 [Nick Bugajski] - -* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 [Jonathan del Strother] - -* Change plings to the more conventional quotes in the documentation. Closes #10104 [Jack Danger Canty] - -* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 [Jack Danger Canty] - -* Ensure that column names are quoted. Closes #10134 [wesley.moxam] - -* Smattering of grammatical fixes to documentation. Closes #10083 [Bob Silva] - -* Enhance explanation with more examples for attr_accessible macro. Closes #8095 [fearoffish, Marcel Molina Jr.] - -* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 [Pratik Naik] - -* Explain semantics of having several different AR instances in a transaction block. Closes #9036 [jacobat, Marcel Molina Jr.] - -* Update Schema documentation to use updated sexy migration notation. Closes #10086 [Sam Granieri] - -* Make fixtures work with the new test subclasses. [Tarmo Tänav, Michael Koziarski] - -* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 [RubyRedRick] - # Find users with an avatar - User.find(:all, :joins => :avatar) - - # Find posts with a high-rated comment. - Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3') - -* Associations: speedup duplicate record check. #10011 [Pratik Naik] - -* Make sure that << works on has_many associations on unsaved records. Closes #9989 [Josh Susser] - -* Allow association redefinition in subclasses. #9346 [wildchild] - -* Fix has_many :through delete with custom foreign keys. #6466 [naffis] - -* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README) - - stable, autogenerated IDs - - specify associations (belongs_to, has_one, has_many) by label, not ID - - specify HABTM associations as inline lists - - autofill timestamp columns - - support YAML defaults - - fixture label interpolation - Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 [John Barnette] - -* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 [boone, rmm5t] - -* Update add_index documentation to use new options api. Closes #9787 [Kamal Fariz Mahyuddin] - -* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 [krishna] - -* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 [sur] - -* Limited eager loading no longer ignores scoped :order. Closes #9561 [Jack Danger Canty, Josh Peek] - -* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 [brandon, Chris Cruft] - -* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 [Chris Cruft] - -* Ensure that mysql quotes table names with database names correctly. Closes #9911 [crayz] - - "foo.bar" => "`foo`.`bar`" - -* Complete the assimilation of Sexy Migrations from ErrFree [Chris Wanstrath, PJ Hyett] - http://errtheblog.com/post/2381 - -* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 [Jack Danger Canty] - -* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 [Bryan Helmkamp] - -* Refactor association create and build so before & after callbacks behave consistently. #8854 [Pratik Naik, mortent] - -* Quote table names. Defaults to column quoting. #4593 [Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper] - -* Alias association #build to #new so it behaves predictably. #8787 [Pratik Naik] - -* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 [saimonmoore, Rick Olson] - -* Observers can observe model names as symbols properly now. Closes #9869 [queso] - -* find_and_(initialize|create)_by methods can now properly initialize protected attributes [Tobias Lütke] - -* belongs_to infers the foreign key from the association name instead of from the class name. [Jeremy Kemper] - -* PostgreSQL: support multiline default values. #7533 [Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav] - -* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 [Jonathan Viney, Tarmo Tänav] - -* validates_uniqueness_of behaves well with abstract superclasses and -single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat] - -* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 [Henrik N] - -* Speedup database date/time parsing. [Jeremy Kemper, Tarmo Tänav] - -* Fix calling .clear on a has_many :dependent=>:delete_all association. [Tarmo Tänav] - -* Allow change_column to set NOT NULL in the PostgreSQL adapter [Tarmo Tänav] - -* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. [Rick Olson] - -* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. [Rick Olson] - -* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. [Jeremy Kemper, Derrick Spell] - - -*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.14.2 - 1.15.3] - -* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 [Dan Manges] - - class Comment < ActiveRecord::Base - # Automatically sets Article#comments_count as readonly. - belongs_to :article, :counter_cache => :comments_count - end - - class Article < ActiveRecord::Base - attr_readonly :approved_comments_count - end - -* Make size for has_many :through use counter cache if it exists. Closes #9734 [Xavier Shay] - -* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. [Jeremy Kemper] - -* Extract Oracle, SQLServer, and Sybase adapters into gems. [Jeremy Kemper] - -* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 [Frederick Cheung] - -* Correctly quote id list for limited eager loading. #7482 [tmacedo] - -* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 [valeksenko] - -* Fixed rename_column for SQLite when using symbols for the column names #8616 [drodriguez] - -* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 [Robby Russell, Tarmo Tänav] - -* Added ActiveRecord::Base#to_json/from_json [David Heinemeier Hansson, Cheah Chu Yeow] - -* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example: - - xml = "<person><name>David</name></person>" - Person.new.from_xml(xml).name # => "David" - -* Define dynamic finders as real methods after first usage. [bscofield] - -* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. [Jeremy Kemper] - -* Associations macros accept extension blocks alongside modules. #9346 [Josh Peek] - -* Speed up and simplify query caching. [Jeremy Kemper] - -* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 [Michael Schuerig] - -* Eager loading respects explicit :joins. #9496 [dasil003] - -* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 [Jeremy Kemper] - -* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. [Jeremy Kemper] - -* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 [TimoMihaljov/brandon] - -* Fix association writer with :dependent => :nullify. #7314 [Jonathan Viney] - -* OpenBase: update for new lib and latest Rails. Support migrations. #8748 [dcsesq] - -* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 [Pratik Naik] - -* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 [Josh Peek] - -* Moved acts_as_list into a plugin of the same name on the official Rails svn. [Josh Peek] - -* Explicitly require active_record/query_cache before using it. [Jeremy Kemper] - -* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. [Rick Olson, marclove] - -* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. [Jeremy Kemper] - -* Fixed that eager loading queries and with_scope should respect the :group option [David Heinemeier Hansson] - -* Improve performance and functionality of the postgresql adapter. Closes #8049 [roderickvd] - - For more information see: http://dev.rubyonrails.org/ticket/8049 - -* Don't clobber includes passed to has_many.count [Jack Danger Canty] - -* Make sure has_many uses :include when counting [Jack Danger Canty] - -* Change the implementation of ActiveRecord's attribute reader and writer methods [Michael Koziarski] - - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns. - - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns. - - Move method definition to the class, instead of the instance - - Always generate the readers, writers and predicate methods. - -* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. [Rick Olson] - -# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik] - -* Added :unless clause to validations #8003 [monki]. Example: - - def using_open_id? - !identity_url.blank? - end - - validates_presence_of :identity_url, :if => using_open_id? - validates_presence_of :username, :unless => using_open_id? - validates_presence_of :password, :unless => using_open_id? - -* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 [Pratik Naik] - -* Fix and properly document/test count(column_name) usage. Closes #8999 [Pratik Naik] - -* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 [Pratik Naik] - -* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 [Josh Susser] - - OLD - belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id - - NEW - belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id - -* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 [Pratik Naik] - -* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 [Pratik Naik] - -* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 [dasil003] - -* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, [Manfred Stienstra, jwilger] - -* Define collection singular ids method for has_many :through associations. #8763 [Pratik Naik] - -* Array attribute conditions work with proxied association collections. #8318 [Kamal Fariz Mahyuddin, theamazingrando] - -* Fix polymorphic has_one associations declared in an abstract class. #8638 [Pratik Naik, Dax Huiberts] - -* Fixed validates_associated should not stop on the first error. #4276 [mrj, Manfred Stienstra, Josh Peek] - -* Rollback if commit raises an exception. #8642 [kik, Jeremy Kemper] - -* Update tests' use of fixtures for the new collections api. #8726 [Kamal Fariz Mahyuddin] - -* Save associated records only if the association is already loaded. #8713 [Blaine] - -* MySQL: fix show_variable. #8448 [matt, Jeremy Kemper] - -* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 [Michael Schuerig] - -* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 [technomancy, Josh Peek] - -* Calculations support non-numeric foreign keys. #8154 [Kamal Fariz Mahyuddin] - -* with_scope is protected. #8524 [Josh Peek] - -* Quickref for association methods. #7723 [marclove, Mindsweeper] - -* Calculations: return nil average instead of 0 when there are no rows to average. #8298 [davidw] - -* acts_as_nested_set: direct_children is sorted correctly. #4761 [Josh Peek, rails@33lc0.net] - -* Raise an exception if both attr_protected and attr_accessible are declared. #8507 [stellsmi] - -* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 [marclove, lorenjohnson] - -* Allow nil serialized attributes with a set class constraint. #7293 [sandofsky] - -* Oracle: support binary fixtures. #7987 [Michael Schoen] - -* Fixtures: pull fixture insertion into the database adapters. #7987 [Michael Schoen] - -* Announce migration versions as they're performed. [Jeremy Kemper] - -* find gracefully copes with blank :conditions. #7599 [Dan Manges, johnnyb] - -* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 [Bob Silva, Dan Kubb, Josh Peek] - -* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 [matt] - -* Find with a list of ids supports limit/offset. #8437 [hrudududu] - -* Optimistic locking: revert the lock version when an update fails. #7840 [plang] - -* Migrations: add_column supports custom column types. #7742 [jsgarvin, Theory] - -* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. [Jeremy Kemper] - -* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 [Jack Danger Canty, Josh Peek, Rick Olson] - -* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 [mmangino@elevatedrails.com] - -* Fix column type detection while loading fixtures. Closes #7987 [roderickvd] - -* Document deep eager includes. #6267 [Josh Susser, Dan Manges] - -* Document warning that associations names shouldn't be reserved words. #4378 [murphy@cYcnus.de, Josh Susser] - -* Sanitize Base#inspect. #8392, #8623 [Nik Wakelin, jnoon] - -* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. [Michael Koziarski] - -* Oracle: extract column length for CHAR also. #7866 [ymendel] - -* Document :allow_nil option for validates_acceptance_of since it defaults to true. [tzaharia] - -* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. [Jack Danger Canty] - -* Add documentation caveat about when to use count_by_sql. [fearoffish] - -* Enhance documentation for increment_counter and decrement_counter. [fearoffish] - -* Provide brief introduction to what optimistic locking is. [fearoffish] - -* Add documentation for :encoding option to mysql adapter. [marclove] - -* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example: - - create_table "products" do |t| - t.column "shop_id", :integer - t.column "creator_id", :integer - t.column "name", :string, :default => "Untitled" - t.column "value", :string, :default => "Untitled" - t.column "created_at", :datetime - t.column "updated_at", :datetime - end - - ...can now be written as: - - create_table :products do |t| - t.integer :shop_id, :creator_id - t.string :name, :value, :default => "Untitled" - t.timestamps - end - -* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. [Michael Koziarski, jstrachan] - -* Improve performance of calling .create on has_many :through associations. [evan] - -* Improved cloning performance by relying less on exception raising #8159 [Blaine] - -* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> [David Heinemeier Hansson] - -* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls [David Heinemeier Hansson] - -* Small additions and fixes for ActiveRecord documentation. Closes #7342 [Jeremy McAnally] - -* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. [court3nay] - -* SQLite: binary escaping works with $KCODE='u'. #7862 [tsuka] - -* Base#to_xml supports serialized attributes. #7502 [jonathan] - -* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. [Jeremy Kemper] - -* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 [Michael Koziarski, Jeremy Kemper] - -* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. [Jeremy Kemper] - -* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 [Josh Susser] - -* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. [Michael Koziarski] - -* Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool] - -* Consistent public/protected/private visibility for chained methods. #7813 [Dan Manges] - -* Oracle: fix quoted primary keys and datetime overflow. #7798 [Michael Schoen] - -* Consistently quote primary key column names. #7763 [toolmantim] - -* Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley] - -* DateTimes assume the default timezone. #7764 [Geoff Buesing] - -* Sybase: hide timestamp columns since they're inherently read-only. #7716 [Mike Joyce] - -* Oracle: overflow Time to DateTime. #7718 [Michael Schoen] - -* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 [flowdelic, toolmantim] - -* Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins] - -* Test DateTime native type in migrations, including an edge case with dates -during calendar reform. #7649, #7724 [fedot, Geoff Buesing] - -* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 [Jakob Skjerning, Tom Ward] - -* SQLServer: recognize real column type as Ruby float. #7057 [sethladd, Tom Ward] - -* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 [Manfred Stienstra] - -* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example: - - transaction do |transaction| - david.withdrawal(100) - mary.deposit(100) - transaction.rollback! # rolls back the transaction that was otherwise going to be successful - end - -* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method [Jamis Buck] - -* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however [Tobias Lütke] - Task.cache { Task.find(1); Task.find(1) } # => 1 query - -* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck] - -* Oracle: fix lob and text default handling. #7344 [gfriedrich, Michael Schoen] - -* SQLServer: don't choke on strings containing 'null'. #7083 [Jakob Skjerning] - -* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 [Dan Kubb] - -* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 [sandofsky, Assaf] - -* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 [Jonathan Viney, timc] - -* Use Date#to_s(:db) for quoted dates. #7411 [Michael Schoen] - -* Don't create instance writer methods for class attributes. Closes #7401 [Rick Olson] - -* Docs: validations examples. #7343 [zackchandler] - -* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 [sandofsky] - -* Fixtures use the table name and connection from set_fixture_class. #7330 [Anthony Eden] - -* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 [Josh Susser] - -* Fix minor doc typos. Closes #7157 [Josh Susser] - -* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 [Josh Susser] - -* SQLServer: quote table name in indexes query. #2928 [keithm@infused.org] - -* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 [BertG, nick+rails@ag.arizona.edu] - -* Make sure sqlite3 driver closes open connections on disconnect [Rob Rasmussen] - -* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [Jeremy McAnally] - -* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [Dan Manges, Jeremy Kemper] - -* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, Manfred Stienstra, altano@bigfoot.com] - -* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen] - -* MySQL: retain SSL settings on reconnect. #6976 [randyv2] - -* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. [Cody Fauser] - -* SQLServer: handle [quoted] table names. #6635 [rrich] - -* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser] - -* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen] - -* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 [Dan Manges] - Student.find(:all, :conditions => { :grade => 9..12 }) - -* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler] - -* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell] - -* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot] - -* Bring the sybase adapter up to scratch for 1.2 release. [jsheets] - -* Rollback new_record? and id when an exception is raised in a save callback. #6910 [Ben Curren, outerim] - -* Pushing a record on an association collection doesn't unnecessarily load all the associated records. [Obie Fernandez, Jeremy Kemper] - -* Oracle: fix connection reset failure. #6846 [leonlleslie] - -* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper] - -* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool] - -* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 [Alexander Dymo, Tobias Lütke] - -* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper] - -* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute [Cody Fauser] - -* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form [David Heinemeier Hansson] - -* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 [Zach Dennis] - -* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov] - -* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 [Jonathan Viney] - -* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz] - -* Run validations in the order they were declared. #6657 [obrie] - -* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper] - -* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 [martin] - -* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen] - -* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen] - -* Don't inspect unloaded associations. #2905 [lmarlow] - -* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 [careo, lukfugl] - -* Cache inheritance_column. #6592 [Stefan Kaes] - -* Firebird: decimal/numeric support. #6408 [macrnic] - -* make add_order a tad faster. #6567 [Stefan Kaes] - -* Find with :include respects scoped :order. #5850 - -* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper] - find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } - -* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 [Si] - -* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. [Jeremy Kemper] - -* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 [Bob Silva] - -* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes] - -* Deprecation: object transactions warning. [Jeremy Kemper] - -* has_one :dependent => :nullify ignores nil associates. #4848, #6528 [bellis@deepthought.org, janovetz, Jeremy Kemper] - -* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen] - -* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie] - -* Document other options available to migration's add_column. #6419 [grg] - -* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper] - -* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney] - -* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters [Rick Olson] - -* Restore eager condition interpolation, document it's differences [Rick Olson] - -* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 [Jacob Fugal, Jeremy Kemper] - -* Add #delete support to has_many :through associations. Closes #6049 [Martin Landers] - -* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 [Rick Olson] - -* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 [turnip@turnipspatch.com] - -* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 [wreese@gmail.com] - -* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 [jonathan] - -* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 [Bob Silva] - -* The has_many create method works with polymorphic associations. #6361 [Dan Peterson] - -* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 [Stefan Kaes] - -* save! shouldn't validate twice. #6324 [maiha, Bob Silva] - -* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 [Michael Schuerig] - -* Add an attribute reader method for ActiveRecord::Base.observers [Rick Olson] - -* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 [Bob Silva] - -* has_one associations with a nil target may be safely marshaled. #6279 [norbauer, Jeremy Kemper] - -* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects [Michael Koziarski] - -* Add a :namespace option to AR::Base#to_xml [Michael Koziarski] - -* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. [Jeremy Kemper] - -* Mock Time.now for more accurate Touch mixin tests. #6213 [Dan Peterson] - -* Improve yaml fixtures error reporting. #6205 [Bruce Williams] - -* Rename AR::Base#quote so people can use that name in their models. #3628 [Michael Koziarski] - -* Add deprecation warning for inferred foreign key. #6029 [Josh Susser] - -* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 [jimw@mysql.com] - -* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser] - -* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 [Bob Silva] - -* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward] - -* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher] - -* Deprecation: update docs. #5998 [Jakob Skjerning, Kevin Clark] - -* Add some XmlSerialization tests for ActiveRecord [Rick Olson] - -* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com] - -* Tighten rescue clauses. #5985 [james@grayproductions.net] - -* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck] - -* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney] - -* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 [Jonathan Viney] - -* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi] - -* SQLServer: fix eager association test. #5901 [Tom Ward] - -* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark] - -* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com] - -* Migrations: gracefully handle missing migration files. #5857 [eli.gordon@gmail.com] - -* MySQL: update test schema for MySQL 5 strict mode. #5861 [Tom Ward] - -* to_xml: correct naming of included associations. #5831 [Josh Starcher] - -* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 [Josh Susser] - -* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. [Jeremy Kemper] - - # Create a tagging to associate the post and tag. - post.tags << Tag.find_by_name('old') - post.tags.create! :name => 'general' - - # Would have been: - post.taggings.create!(:tag => Tag.find_by_name('finally') - transaction do - post.taggings.create!(:tag => Tag.create!(:name => 'general')) - end - -* Cache nil results for :included has_one associations also. #5787 [Michael Schoen] - -* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Lütke] - -* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper] - Example: Invoice::Lineitem is given table name invoice_lineitems - -* Migrations: uniquely name multicolumn indexes so you don't have to. [Jeremy Kemper] - # people_active_last_name_index, people_active_deactivated_at_index - add_index :people, [:active, :last_name] - add_index :people, [:active, :deactivated_at] - remove_index :people, [:active, :last_name] - remove_index :people, [:active, :deactivated_at] - - WARNING: backward-incompatibility. Multicolumn indexes created before this - revision were named using the first column name only. Now they're uniquely - named using all indexed columns. - - To remove an old multicolumn index, remove_index :table_name, :first_column - -* Fix for deep includes on the same association. [richcollins@gmail.com] - -* Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark] - -* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson] - -* Document find's :from option. Closes #5762. [andrew@redlinesoftware.com] - -* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com] - -* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar] - -* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael Schoen] - -* Add documentation for how to disable timestamps on a per model basis. Closes #5684. [matt@mattmargolis.net Marcel Molina Jr.] - -* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney] - -* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson] - -* Formally deprecate the deprecated finders. [Michael Koziarski] - -* Formally deprecate rich associations. [Michael Koziarski] - -* Fixed that default timezones for new / initialize should uphold utc setting #5709 [daniluk@yahoo.com] - -* Fix announcement of very long migration names. #5722 [blake@near-time.com] - -* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com] - -* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com] - -* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: - - assert (Topic.exists?(:author_name => "David")) - assert (Topic.exists?(:author_name => "Mary", :approved => true)) - assert (Topic.exists?(["parent_id = ?", 1])) - -* Schema dumper quotes date :default values. [Dave Thomas] - -* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson] - -* Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper] - -* Patch sql injection vulnerability when using integer or float columns. [Jamis Buck] - -* Allow #count through a has_many association to accept :include. [Dan Peterson] - -* create_table rdoc: suggest :id => false for habtm join tables. [Zed Shaw] - -* PostgreSQL: return array fields as strings. #4664 [Robby Russell] - -* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 [Tom Ward] - -* SQLServer: fix db:schema:dump case-sensitivity. #4684 [Will Rogers] - -* Oracle: BigDecimal support. #5667 [Michael Schoen] - -* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 [robbat2@gentoo.org, work@ashleymoran.me.uk] - -* Firebird migrations support. #5337 [Ken Kunz <kennethkunz@gmail.com>] - -* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com] - -* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>] - -* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net] - -* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com] - -* Clearer has_one/belongs_to model names (account has_one :user). #5632 [matt@mattmargolis.net] - -* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 [Michael Schoen] - -* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 [Michael Schoen] - -* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org] - -* Minor tweak to improve performance of ActiveRecord::Base#to_param. - -* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au] - -* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper] - -* rake build_mysql_database grants permissions to rails@localhost. #5501 [brianegge@yahoo.com] - -* PostgreSQL: support microsecond time resolution. #5492 [alex@msgpad.com] - -* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. - -* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. [Sam Stephenson] - -* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). [Shugo Maeda] - # Obtain an exclusive lock on person 1 so we can safely increment visits. - Person.transaction do - # select * from people where id=1 for update - person = Person.find(1, :lock => true) - person.visits += 1 - person.save! - end - -* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. [Jeremy Kemper] - -* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. [Jeremy Kemper] - -* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. [Nicholas Seckar] - -* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) - -* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization [David Heinemeier Hansson] - -* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: - - Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) - -...is the same as: - - Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) - - This makes it easier to pass in the options from a form or otherwise outside. - - -* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 [kennethkunz@gmail.com] - -* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 [alex@purefiction.net] - -* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 [greg@lapcominc.com] - -* Fixed problems with eager loading and counting on SQL Server #5212 [kajism@yahoo.com] - -* Fixed that count distinct should use the selected column even when using :include #5251 [anna@wota.jp] - -* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 [alex@purefiction.net] - -* Allow models to override to_xml. #4989 [Blair Zajac <blair@orcaware.com>] - -* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 [shimbo@is.naist.jp] - -* Records and arrays of records are bound as quoted ids. [Jeremy Kemper] - Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) - Foo.find(:first, :conditions => ['bar_id = ?', bar]) - -* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty [David Heinemeier Hansson] - -* Add a list of regexes assert_queries skips in the ActiveRecord test suite. [Rick Olson] - -* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [Josh Susser] - -* Provide Association Extensions access to the instance that the association is being accessed from. - Closes #4433 [Josh Susser] - -* Update OpenBase adaterp's maintainer's email address. Closes #5176. [Derrick Spell] - -* Add a quick note about :select and eagerly included associations. [Rick Olson] - -* Add docs for the :as option in has_one associations. Closes #5144 [cdcarter@gmail.com] - -* Fixed that has_many collections shouldn't load the entire association to do build or create [David Heinemeier Hansson] - -* Added :allow_nil option for aggregations #5091 [Ian White] - -* Fix Oracle boolean support and tests. Closes #5139. [Michael Schoen] - -* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) [Jeremy Kemper] - -* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 [info@loobmedia.com] - -* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. [pdcawley@bofh.org.uk] - -* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 [keegan@thebasement.org] - -* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 [kajism@yahoo.com] - -* Allow :uniq => true with has_many :through associations. [Jeremy Kemper] - -* Ensure that StringIO is always available for the Schema dumper. [Marcel Molina Jr.] - -* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com] - -* Replace superfluous name_to_class_name variant with camelize. [Marcel Molina Jr.] - -* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.] - -* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.] - -* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>] - -* Update FrontBase adapter to check binding version. Closes #4920. [mlaster@metavillage.com] - -* New Frontbase connections don't start in auto-commit mode. Closes #4922. [mlaster@metavillage.com] - -* When grouping, use the appropriate option key. [Marcel Molina Jr.] - -* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. [Marcel Molina Jr.] - -* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com] - -* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>] - -* Fix syntax error in documentation. Closes #4679. [Mislav Marohnić] - -* Add Oracle support for CLOB inserts. Closes #4748. [schoenm@earthlink.net sandra.metz@duke.edu] - -* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. [kajism@yahoo.com] - -* Add support for :order option to with_scope. Closes #3887. [eric.daspet@survol.net] - -* Prettify output of schema_dumper by making things line up. Closes #4241 [Caio Chassot <caio@v2studio.com>] - -* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. [mlaster@metavillage.com] - -* Sybase Adapter type conversion cleanup. Closes #4736. [dev@metacasa.net] - -* Fix bug where calculations with long alias names return null. [Rick Olson] - -* Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick Olson] - - @post.tags << @tag # BAD - @post.taggings.create(:tag => @tag) # GOOD - -* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick Olson] - -* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com] - -* Add ActiveRecord::Errors#to_xml [Jamis Buck] - -* Properly quote index names in migrations (closes #4764) [John Long] - -* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. [Rick Olson] - -* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson] - -* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson] - -* DRY up association collection reader method generation. [Marcel Molina Jr.] - -* DRY up and tweak style of the validation error object. [Marcel Molina Jr.] - -* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick Olson] - - class Account < ActiveRecord::Base - validates_uniqueness_of :email, :case_sensitive => false - end - -* Allow multiple association extensions with :extend option (closes #4666) [Josh Susser] - - class Account < ActiveRecord::Base - has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] - end - - *1.15.3* (March 12th, 2007) - - * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool] - - * Consistently quote primary key column names. #7763 [toolmantim] - - * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley] - - * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins] - - -*1.15.2* (February 5th, 2007) - -* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 [Dan Manges] - Student.find(:all, :conditions => { :grade => 9..12 }) - -* Don't create instance writer methods for class attributes. [Rick Olson] - -* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck] - -* SQLServer: don't choke on strings containing 'null'. #7083 [Jakob Skjerning] - -* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 [Si] - -* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 [Jonathan Viney, timc] - -* Fixtures use the table name and connection from set_fixture_class. #7330 [Anthony Eden] - -* SQLServer: quote table name in indexes query. #2928 [keithm@infused.org] - - -*1.15.1* (January 17th, 2007) - -* Fix nodoc breaking of adapters - - -*1.15.0* (January 16th, 2007) - -* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [Jeremy McAnally] - -* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [Dan Manges, Jeremy Kemper] - -* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, Manfred Stienstra, altano@bigfoot.com] - -* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen] - -* MySQL: retain SSL settings on reconnect. #6976 [randyv2] - -* SQLServer: handle [quoted] table names. #6635 [rrich] - -* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser] - -* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen] - -* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler] - -* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell] - -* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot] - -* Bring the sybase adapter up to scratch for 1.2 release. [jsheets] - -* Oracle: fix connection reset failure. #6846 [leonlleslie] - -* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper] - -* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool] - -* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper] - -* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper] - find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } - -* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov] - -* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper] - -* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz] - -* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen] - -* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen] - -* Firebird: decimal/numeric support. #6408 [macrnic] - -* Find with :include respects scoped :order. #5850 - -* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes] - -* Deprecation: object transactions warning. [Jeremy Kemper] - -* has_one :dependent => :nullify ignores nil associates. #6528 [janovetz, Jeremy Kemper] - -* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen] - -* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie] - -* Document other options available to migration's add_column. #6419 [grg] - -* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper] - -* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney] - -* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters [Rick Olson] - -* Restore eager condition interpolation, document it's differences [Rick Olson] - -* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 [Jacob Fugal, Jeremy Kemper] - -* Add #delete support to has_many :through associations. Closes #6049 [Martin Landers] - -* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 [Rick Olson] - -* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 [turnip@turnipspatch.com] - -* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 [wreese@gmail.com] - -* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 [jonathan] - -* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 [Bob Silva] - -* The has_many create method works with polymorphic associations. #6361 [Dan Peterson] - -* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 [Stefan Kaes] - -* save! shouldn't validate twice. #6324 [maiha, Bob Silva] - -* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 [Michael Schuerig] - -* Add an attribute reader method for ActiveRecord::Base.observers [Rick Olson] - -* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 [Bob Silva] - -* has_one associations with a nil target may be safely marshaled. #6279 [norbauer, Jeremy Kemper] - -* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects [Michael Koziarski] - -* Add a :namespace option to AR::Base#to_xml [Michael Koziarski] - -* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. [Jeremy Kemper] - -* Mock Time.now for more accurate Touch mixin tests. #6213 [Dan Peterson] - -* Improve yaml fixtures error reporting. #6205 [Bruce Williams] - -* Rename AR::Base#quote so people can use that name in their models. #3628 [Michael Koziarski] - -* Add deprecation warning for inferred foreign key. #6029 [Josh Susser] - -* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 [jimw@mysql.com] - -* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser] - -* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward] - -* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher] - -* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com] - -* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck] - -* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney] - -* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 [Jonathan Viney] - -* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi] - -* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark] - -* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com] - -* Migrations: gracefully handle missing migration files. #5857 [eli.gordon@gmail.com] - -* MySQL: update test schema for MySQL 5 strict mode. #5861 [Tom Ward] - -* to_xml: correct naming of included associations. #5831 [Josh Starcher] - -* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 [Josh Susser] - -* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. [Jeremy Kemper] - - # Create a tagging to associate the post and tag. - post.tags << Tag.find_by_name('old') - post.tags.create! :name => 'general' - - # Would have been: - post.taggings.create!(:tag => Tag.find_by_name('finally') - transaction do - post.taggings.create!(:tag => Tag.create!(:name => 'general')) - end - -* Cache nil results for :included has_one associations also. #5787 [Michael Schoen] - -* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Lütke] - -* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper] - Example: Invoice::Lineitem is given table name invoice_lineitems - -* Migrations: uniquely name multicolumn indexes so you don't have to. [Jeremy Kemper] - # people_active_last_name_index, people_active_deactivated_at_index - add_index :people, [:active, :last_name] - add_index :people, [:active, :deactivated_at] - remove_index :people, [:active, :last_name] - remove_index :people, [:active, :deactivated_at] - - WARNING: backward-incompatibility. Multicolumn indexes created before this - revision were named using the first column name only. Now they're uniquely - named using all indexed columns. - - To remove an old multicolumn index, remove_index :table_name, :first_column - -* Fix for deep includes on the same association. [richcollins@gmail.com] - -* Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark] - -* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson] - -* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com] - -* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar] - -* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael Schoen] - -* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney] - -* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson] - -* Formally deprecate the deprecated finders. [Michael Koziarski] - -* Formally deprecate rich associations. [Michael Koziarski] - -* Fixed that default timezones for new / initialize should uphold utc setting #5709 [daniluk@yahoo.com] - -* Fix announcement of very long migration names. #5722 [blake@near-time.com] - -* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com] - -* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com] - -* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: - - assert (Topic.exists?(:author_name => "David")) - assert (Topic.exists?(:author_name => "Mary", :approved => true)) - assert (Topic.exists?(["parent_id = ?", 1])) - -* Schema dumper quotes date :default values. [Dave Thomas] - -* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson] - -* Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper] - -* Patch sql injection vulnerability when using integer or float columns. [Jamis Buck] - -* Allow #count through a has_many association to accept :include. [Dan Peterson] - -* create_table rdoc: suggest :id => false for habtm join tables. [Zed Shaw] - -* PostgreSQL: return array fields as strings. #4664 [Robby Russell] - -* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 [Tom Ward] - -* SQLServer: fix db:schema:dump case-sensitivity. #4684 [Will Rogers] - -* Oracle: BigDecimal support. #5667 [Michael Schoen] - -* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 [robbat2@gentoo.org, work@ashleymoran.me.uk] - -* Firebird migrations support. #5337 [Ken Kunz <kennethkunz@gmail.com>] - -* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com] - -* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net] - -* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com] - -* Clearer has_one/belongs_to model names (account has_one :user). #5632 [matt@mattmargolis.net] - -* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 [Michael Schoen] - -* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 [Michael Schoen] - -* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org] - -* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au] - -* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper] - -* rake build_mysql_database grants permissions to rails@localhost. #5501 [brianegge@yahoo.com] - -* PostgreSQL: support microsecond time resolution. #5492 [alex@msgpad.com] - -* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. - -* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. [Sam Stephenson] - -* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). [Shugo Maeda] - # Obtain an exclusive lock on person 1 so we can safely increment visits. - Person.transaction do - # select * from people where id=1 for update - person = Person.find(1, :lock => true) - person.visits += 1 - person.save! - end - -* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. [Jeremy Kemper] - -* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. [Jeremy Kemper] - -* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. [Nicholas Seckar] - -* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) - -* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization [David Heinemeier Hansson] - -* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: - - Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) - -...is the same as: - - Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) - - This makes it easier to pass in the options from a form or otherwise outside. - - -* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 [kennethkunz@gmail.com] - -* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 [alex@purefiction.net] - -* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 [greg@lapcominc.com] - -* Fixed problems with eager loading and counting on SQL Server #5212 [kajism@yahoo.com] - -* Fixed that count distinct should use the selected column even when using :include #5251 [anna@wota.jp] - -* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 [alex@purefiction.net] - -* Allow models to override to_xml. #4989 [Blair Zajac <blair@orcaware.com>] - -* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 [shimbo@is.naist.jp] - -* Records and arrays of records are bound as quoted ids. [Jeremy Kemper] - Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) - Foo.find(:first, :conditions => ['bar_id = ?', bar]) - -* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty [David Heinemeier Hansson] - -* Add a list of regexes assert_queries skips in the ActiveRecord test suite. [Rick Olson] - -* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [Josh Susser] - -* Provide Association Extensions access to the instance that the association is being accessed from. - Closes #4433 [Josh Susser] - -* Update OpenBase adaterp's maintainer's email address. Closes #5176. [Derrick Spell] - -* Add a quick note about :select and eagerly included associations. [Rick Olson] - -* Add docs for the :as option in has_one associations. Closes #5144 [cdcarter@gmail.com] - -* Fixed that has_many collections shouldn't load the entire association to do build or create [David Heinemeier Hansson] - -* Added :allow_nil option for aggregations #5091 [Ian White] - -* Fix Oracle boolean support and tests. Closes #5139. [Michael Schoen] - -* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) [Jeremy Kemper] - -* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 [info@loobmedia.com] - -* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. [pdcawley@bofh.org.uk] - -* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 [keegan@thebasement.org] - -* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 [kajism@yahoo.com] - -* Allow :uniq => true with has_many :through associations. [Jeremy Kemper] - -* Ensure that StringIO is always available for the Schema dumper. [Marcel Molina Jr.] - -* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com] - -* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>] - -* When grouping, use the appropriate option key. [Marcel Molina Jr.] - -* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com] - -* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>] - -* Fix syntax error in documentation. Closes #4679. [Mislav Marohnić] - -* Add Oracle support for CLOB inserts. Closes #4748. [schoenm@earthlink.net sandra.metz@duke.edu] - -* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. [kajism@yahoo.com] - -* Add support for :order option to with_scope. Closes #3887. [eric.daspet@survol.net] - -* Prettify output of schema_dumper by making things line up. Closes #4241 [Caio Chassot <caio@v2studio.com>] - -* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. [mlaster@metavillage.com] - -* Sybase Adapter type conversion cleanup. Closes #4736. [dev@metacasa.net] - -* Fix bug where calculations with long alias names return null. [Rick Olson] - -* Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick Olson] - - @post.tags << @tag # BAD - @post.taggings.create(:tag => @tag) # GOOD - -* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick Olson] - -* Add ActiveRecord::Errors#to_xml [Jamis Buck] - -* Properly quote index names in migrations (closes #4764) [John Long] - -* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. [Rick Olson] - -* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson] - -* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson] - -* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick Olson] - - class Account < ActiveRecord::Base - validates_uniqueness_of :email, :case_sensitive => false - end - -* Allow multiple association extensions with :extend option (closes #4666) [Josh Susser] - - class Account < ActiveRecord::Base - has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] - end - - -*1.14.4* (August 8th, 2006) - -* Add warning about the proper way to validate the presence of a foreign key. #4147 [Francois Beausoleil <francois.beausoleil@gmail.com>] - -* Fix syntax error in documentation. #4679 [Mislav Marohnić] - -* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com] - - -*1.14.3* (June 27th, 2006) - -* Fix announcement of very long migration names. #5722 [blake@near-time.com] - -* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>] - -* Properly quote index names in migrations (closes #4764) [John Long] - -* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson] - -* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson] - - -*1.14.2* (April 9th, 2006) - -* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen] - - -*1.14.1* (April 6th, 2006) - -* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. [Nicholas Seckar] - -* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) [Lars Pind] - -* Enable Limit/Offset in Calculations (closes #4558) [lmarlow] - -* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) [Rick Olson] - -* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 [lagroue@free.fr] - -* Allow AR::Base#respond_to? to behave when @attributes is nil [Ryan Davis] - -* Support eager includes when going through a polymorphic has_many association. [Rick Olson] - -* Added support for eagerly including polymorphic has_one associations. (closes #4525) [Rick Olson] - - class Post < ActiveRecord::Base - has_one :tagging, :as => :taggable - end - - Post.find :all, :include => :tagging - -* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many [Rick Olson] - -* Added support for going through a polymorphic has_many association: (closes #4401) [Rick Olson] - - class PhotoCollection < ActiveRecord::Base - has_many :photos, :as => :photographic - belongs_to :firm - end - - class Firm < ActiveRecord::Base - has_many :photo_collections - has_many :photos, :through => :photo_collections - end - -* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. [ruben.nine@gmail.com] - -* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. [Florian Weber] - -* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) [Stefan] - -* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) [Rick Olson] - -* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model [David Heinemeier Hansson] - -* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) [David Heinemeier Hansson] - -* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). [Marcel Mollina Jr.] - -* Fixed broken OCIAdapter #4457 [Michael Schoen] - - -*1.14.0* (March 27th, 2006) - -* Replace 'rescue Object' with a finer grained rescue. Closes #4431. [Nicholas Seckar] - -* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table [Rick Olson] - -* Add support for :include to with_scope [andrew@redlinesoftware.com] - -* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 [Michael Schoen] - -* Change periods (.) in table aliases to _'s. Closes #4251 [jeff@ministrycentered.com] - -* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 [Rick Olson] - -* Fixed issue that kept :select options from being scoped [Rick Olson] - -* Fixed db_schema_import when binary types are present #3101 [David Heinemeier Hansson] - -* Fixed that MySQL enums should always be returned as strings #3501 [David Heinemeier Hansson] - -* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. [Rick Olson] - - class Connection < ActiveRecord::Base - belongs_to :user - belongs_to :channel - end - - class Channel < ActiveRecord::Base - has_many :connections - has_many :contacts, :through => :connections, :class_name => 'User' # OLD - has_many :contacts, :through => :connections, :source => :user # NEW - end - -* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 [contact@maik-schmidt.de] - -* Allow overriding of find parameters in scoped has_many :through calls [Rick Olson] - - In this example, :include => false disables the default eager association from loading. :select changes the standard - select clause. :joins specifies a join that is added to the end of the has_many :through query. - - class Post < ActiveRecord::Base - has_many :tags, :through => :taggings, :include => :tagging do - def add_joins_and_select - find :all, :select => 'tags.*, authors.id as author_id', :include => false, - :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' - end - end - end - -* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson] - -* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney] - -* Quit ignoring default :include options in has_many :through calls [Mark James] - -* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) [Jonathan Viney] - -* Eager Loading support added for has_many :through => :has_many associations (see below). [Rick Olson] - -* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: - - class Firm < ActiveRecord::Base - has_many :clients - has_many :invoices, :through => :clients - end - - class Client < ActiveRecord::Base - belongs_to :firm - has_many :invoices - end - - class Invoice < ActiveRecord::Base - belongs_to :client - end - -* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) [Josh Susser] - -* Fixed has_many :through to include :conditions set on the :through association. closes #4020 [Jonathan Viney] - -* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) [andylien@gmail.com / Rick Olson] - -* SQL Server adapter gets some love #4298 [Ryan Tomayko] - -* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 [derrickspell@cdmplus.com] - -* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): - - Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') - -* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. [Rick Olson] - -* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 [Michael Koziarski] - -* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 [Michael Koziarski] - -* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 [Tom Ward] - -* Fixed that Migration#execute would have the table name prefix appended to its query #4110 [mark.imbriaco@pobox.com] - -* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) [Jamis Buck] - -* Use association's :conditions when eager loading. [Jeremy Evans] #4144 - -* Alias the has_and_belongs_to_many join table on eager includes. #4106 [Jeremy Evans] - - This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. - - Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') - -* Oracle adapter gets some love #4230 [Michael Schoen] - - * Changes :text to CLOB rather than BLOB [Moses Hohman] - * Fixes an issue with nil numeric length/scales (several) - * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] - * Tweaks a unit test to get it all green again - * Adds support for #current_database - -* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 [Rick Olson] - - class CachedModel < ActiveRecord::Base - self.abstract_class = true - end - - class Post < CachedModel - end - - CachedModel.abstract_class? - => true - - Post.abstract_class? - => false - - Post.base_class - => Post - - Post.table_name - => 'posts' - -* Allow :dependent options to be used with polymorphic joins. #3820 [Rick Olson] - - class Foo < ActiveRecord::Base - has_many :attachments, :as => :attachable, :dependent => :delete_all - end - -* Nicer error message on has_many :through when :through reflection can not be found. #4042 [court3nay] - -* Upgrade to Transaction::Simple 1.3 [Jamis Buck] - -* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model [Rick Olson] - -* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com] - -* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 [johan@johansorensen.com] - -* Dynamically set allow_concurrency. #4044 [Stefan Kaes] - -* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: - - topic.to_xml - - ...returns: - - <?xml version="1.0" encoding="UTF-8"?> - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <id type="integer">1</id> - <approved type="boolean">false</approved> - <replies-count type="integer">0</replies-count> - <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> - <written-on type="datetime">2003-07-16 09:28:00</written-on> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - ...and you can configure with: - - topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) - - ...that'll return: - - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <approved type="boolean">false</approved> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - You can even do load first-level associations as part of the document: - - firm.to_xml :include => [ :account, :clients ] - - ...that'll return something like: - - <?xml version="1.0" encoding="UTF-8"?> - <firm> - <id type="integer">1</id> - <rating type="integer">1</rating> - <name>37signals</name> - <clients> - <client> - <rating type="integer">1</rating> - <name>Summit</name> - </client> - <client> - <rating type="integer">1</rating> - <name>Microsoft</name> - </client> - </clients> - <account> - <id type="integer">1</id> - <credit-limit type="integer">50</credit-limit> - </account> - </firm> - -* Allow :counter_cache to take a column name for custom counter cache columns [Jamis Buck] - -* Documentation fixes for :dependent [robby@planetargon.com] - -* Stop the MySQL adapter crashing when views are present. #3782 [Jonathan Viney] - -* Don't classify the belongs_to class, it is already singular #4117 [keithm@infused.org] - -* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. [Rick Olson] - -* Fix quoting of inheritance column for STI eager loading #4098 [Jonathan Viney <jonathan@bluewire.net.nz>] - -* Added smarter table aliasing for eager associations for multiple self joins #3580 [Rick Olson] - - * The first time a table is referenced in a join, no alias is used. - * After that, the parent class name and the reflection name are used. - - Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... - - * Any additional join references get a numerical suffix like '_2', '_3', etc. - -* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. - -* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: - - # cascaded in two levels - >> Author.find(:all, :include=>{:posts=>:comments}) - => authors - +- posts - +- comments - - # cascaded in two levels and normal association - >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in two levels with two has_many associations - >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in three levels - >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) - => companies - +- groups - +- members - +- favorites - -* Make counter cache work when replacing an association #3245 [eugenol@gmail.com] - -* Make migrations verbose [Jamis Buck] - -* Make counter_cache work with polymorphic belongs_to [Jamis Buck] - -* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 [anna@wota.jp] - -* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: - - * Does not support DATE SQL column types; use DATETIME instead. - * Date columns on HABTM join tables are returned as String, not Time. - * Insertions are potentially broken for :polymorphic join tables - * BLOB column access not yet fully supported - -* Clear stale, cached connections left behind by defunct threads. [Jeremy Kemper] - -* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. [Jeremy Kemper] - -* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 [Michael Schoen] - -* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 [David Heinemeier Hansson] - -* Speed up class -> connection caching and stale connection verification. #3979 [Stefan Kaes] - -* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. [Kevin Clark] - -* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 [dblack@wobblini.net] - -* Define attribute query methods to avoid method_missing calls. #3677 [Jonathan Viney] - -* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 [Simon Stapleton, Tom Ward] - -* Added support for nested scopes #3407 [anna@wota.jp]. Examples: - - Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 - - # inner rule is used. (all previous parameters are ignored) - Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') - end - - # parameters are merged - Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 - end - end - -* Fixed db2 connection with empty user_name and auth options #3622 [phurley@gmail.com] - -* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 [Masao Mutoh] - -* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 [Lars Pind] - -* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: - - Person.average :age - Person.minimum :age - Person.maximum :age - Person.sum :salary, :group => :last_name - -* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 [Luke Redpath] - -* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. [Jeremy Kemper] - -* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 [Aggregated by schoenm@earthlink.net] - -* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 [rubyonrails@atyp.de] - -* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [Stefan Kaes] - -* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva] - -* Allow :include to be used with has_many :through associations #3611 [Michael Schoen] - -* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 [Blair Zajac] - -* SQLServer: more compatible limit/offset emulation. #3779 [Tom Ward] - -* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 [Rick Olson] - -* PostgreSQL: correctly parse negative integer column defaults. #3776 [bellis@deepthought.org] - -* Fix problems with count when used with :include [Jeremy Hopple and Kevin Clark] - -* ActiveRecord::RecordInvalid now states which validations failed in its default error message [Tobias Lütke] - -* Using AssociationCollection#build with arrays of hashes should call build, not create [David Heinemeier Hansson] - -* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. [Nicholas Seckar] - -* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 [Maik Schmidt] - -* Support the :column option for remove_index with the PostgreSQL adapter. #3661 [Shugo Maeda] - -* Add documentation for add_index and remove_index. #3600 [Manfred Stienstra <m.stienstra@fngtps.com>] - -* If the OCI library is not available, raise an exception indicating as much. #3593 [Michael Schoen] - -* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. [Rick Olson] - -* Make dynamic finders honor additional passed in :conditions. #3569 [Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.] - -* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. [Nicholas Seckar] - -* Make .count work for has_many associations with multi line finder sql [Michael Schoen] - -* Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jamis Buck] - -* Allow configuration of the column used for optimistic locking [wilsonb@gmail.com] - -* Don't hardcode 'id' in acts as list. [ror@philippeapril.com] - -* Fix date errors for SQLServer in association tests. #3406 [Kevin Clark] - -* Escape database name in MySQL adapter when creating and dropping databases. #3409 [anna@wota.jp] - -* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 [alex.borovsky@gmail.com] - -* .with_scope imposed create parameters now bypass attr_protected [Tobias Lütke] - -* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. [Marcel Molina Jr.] - -* Multiple enhancements and adjustments to DB2 adaptor. #3377 [contact@maik-schmidt.de] - -* Sanitize scoped conditions. [Marcel Molina Jr.] - -* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) [David Heinemeier Hansson] - -* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. [Tobias Lütke] - -* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. [Tobias Lütke] - -* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 [yanowitz-rubyonrails@quantumfoam.org, Florian Weber] - -* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 [wejn@box.cz, Rick Olson, Scott Barron] - -* removed :piggyback in favor of just allowing :select on :through associations. [Tobias Lütke] - -* made method missing delegation to class methods on relation target work on :through associations. [Tobias Lütke] - -* made .find() work on :through relations. [Tobias Lütke] - -* Fix typo in association docs. #3296. [Blair Zajac] - -* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model [Tobias Lütke] - -*1.13.2* (December 13th, 2005) - -* Become part of Rails 1.0 - -* MySQL: allow encoding option for mysql.rb driver. [Jeremy Kemper] - -* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: - - class Post - has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author - end - - post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors - post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors - post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors - -* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson] - -* MySQL: fixes for the bundled mysql.rb driver. #3160 [Justin Forder] - -* SQLServer: fix obscure optimistic locking bug. #3068 [kajism@yahoo.com] - -* SQLServer: support uniqueidentifier columns. #2930 [keithm@infused.org] - -* SQLServer: cope with tables names qualified by owner. #3067 [jeff@ministrycentered.com] - -* SQLServer: cope with columns with "desc" in the name. #1950 [Ron Lusk, Ryan Tomayko] - -* SQLServer: cope with primary keys with "select" in the name. #3057 [rdifrango@captechventures.com] - -* Oracle: active? performs a select instead of a commit. #3133 [Michael Schoen] - -* MySQL: more robust test for nullified result hashes. #3124 [Stefan Kaes] - -* Reloading an instance refreshes its aggregations as well as its associations. #3024 [François Beausoleil] - -* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 [Paul Hammmond] - -* PostgreSQL: more robust sequence name discovery. #3087 [Rick Olson] - -* Oracle: use syntax compatible with Oracle 8. #3131 [Michael Schoen] - -* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. [Jeremy Kemper] - -* Added preliminary support for polymorphic associations [David Heinemeier Hansson] - -* Added preliminary support for join models [David Heinemeier Hansson] - -* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. [jeremy@jthopple.com, Marcel Molina Jr.] - -* Firebird: active? and reconnect! methods for handling stale connections. #428 [Ken Kunz <kennethkunz@gmail.com>] - -* Firebird: updated for FireRuby 0.4.0. #3009 [Ken Kunz <kennethkunz@gmail.com>] - -* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 [Jeremy Kemper] - -* Oracle: active? check pings the database rather than testing the last command status. #428 [Michael Schoen] - -* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 [kajism@yahoo.com] - -* Reloading a model doesn't lose track of its connection. #2996 [junk@miriamtech.com, Jeremy Kemper] - -* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 [colman@rominato.com, Florian Weber, Michael Schoen] - -* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 [Shugo Maeda] - -* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. [Jeremy Kemper] - -* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 [Shugo Maeda] - -* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. [Marcel Molina Jr.] - -* Correct boolean handling in generated reader methods. #2945 [Don Park, Stefan Kaes] - -* Don't generate read methods for columns whose names are not valid ruby method names. #2946 [Stefan Kaes] - -* Document :force option to create_table. #2921 [Blair Zajac <blair@orcaware.com>] - -* Don't add the same conditions twice in has_one finder sql. #2916 [Jeremy Evans] - -* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.] - -* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 [Ken Kunz <kennethkunz@gmail.com>] - -* SQLServer: active? and reconnect! methods for handling stale connections. #428 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 [MarkusQ@reality.com] - -* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 [Michael Schoen <schoenm@earthlink.net>] - -* Correct documentation for Base.delete_all. #1568 [Newhydra] - -* Oracle: test case for column default parsing. #2788 [Michael Schoen <schoenm@earthlink.net>] - -* Update documentation for Migrations. #2861 [Tom Werner <tom@cube6media.com>] - -* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 [Jeremy Kemper] - -* Oracle: Much faster column reflection. #2848 [Michael Schoen <schoenm@earthlink.net>] - -* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. [Jeremy Kemper] - -* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. [Jeremy Kemper] - -* PostgreSQL: correctly discover custom primary key sequences. #2594 [Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper] - -* SQLServer: don't report limits for unsupported field types. #2835 [Ryan Tomayko] - -* Include the Enumerable module in ActiveRecord::Errors. [Rick Bradley <rick@rickbradley.com>] - -* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 [rubyonrails@atyp.de] - -* Don't cast nil or empty strings to a dummy date. #2789 [Rick Bradley <rick@rickbradley.com>] - -* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 [rephorm@rephorm.com] - -* Fix sqlite adaptor's detection of missing dbfile or database declaration. [Nicholas Seckar] - -* Fixed acts_as_list for definitions without an explicit :order #2803 [Jonathan Viney] - -* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. [tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper] - -* Correct handling of complex order clauses with SQL Server limit emulation. #2770 [Tom Ward <tom@popdog.net>, Matt B.] - -* Correct whitespace problem in Oracle default column value parsing. #2788 [rick@rickbradley.com] - -* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 [larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper] - -* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. [Jeremy Kemper] - -* More compatible Oracle column reflection. #2771 [Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>] - - -*1.13.0* (November 7th, 2005) - -* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 [Ryan Tomayko] - -* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: - - has_many :posts, :include => [ :author, :comments ] - -* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: - - Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do - # Find where name = ? and active=true - Comment.find :all, :conditions => ['name = ?', name] - # Create comment associated with :post_id - Comment.create :body => "Hello world" - end - -* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 [Ryan Tomayko] - -* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: - - Comment.constrain(:creation => { :post_id => 5 }) do - # Associated with :post_id - Comment.create :body => "Hello world" - end - - This is rarely used directly, but allows for find_or_create on associations. So you can do: - - # If the tag doesn't exist, a new one is created that's associated with the person - person.tags.find_or_create_by_name("Summer") - -* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: - - # No 'Summer' tag exists - Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") - - # Now the 'Summer' tag does exist - Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") - -* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: - - class Account < ActiveRecord::Base - has_many :people do - def find_or_create_by_name(name) - first_name, *last_name = name.split - last_name = last_name.join " " - - find_or_create_by_first_name_and_last_name(first_name, last_name) - end - end - end - - person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") - person.first_name # => "David" - person.last_name # => "Heinemeier Hansson" - - Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). - -* Omit internal dtproperties table from SQLServer table list. #2729 [Ryan Tomayko] - -* Quote column names in generated SQL. #2728 [Ryan Tomayko] - -* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 [Jeremy Kemper] - -* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). [Jeremy Kemper] - -* Correct fixture behavior when table name pluralization is off. #2719 [Rick Bradley <rick@rickbradley.com>] - -* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 [Dan Peterson] - -* Added migration support for Oracle #2647 [Michael Schoen] - -* Worked around that connection can't be reset if allow_concurrency is off. #2648 [Michael Schoen <schoenm@earthlink.net>] - -* Fixed SQL Server adapter to pass even more tests and do even better #2634 [Ryan Tomayko] - -* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 [Tom Ward] - -* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 [Tom Ward] - -* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 [dansketcher@gmail.com] - -* Constraints are cloned so they can't be inadvertently modified while they're -in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] - -* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 [duane.johnson@gmail.com] - -* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 [Michael Schoen] - -* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 [maik schmidt] - - -*1.12.2* (October 26th, 2005) - -* Allow symbols to rename columns when using SQLite adapter. #2531 [Kevin Clark] - -* Map Active Record time to SQL TIME. #2575, #2576 [Robby Russell <robby@planetargon.com>] - -* Clarify semantics of ActiveRecord::Base#respond_to? #2560 [Stefan Kaes] - -* Fixed Association#clear for associations which have not yet been accessed. #2524 [Patrick Lenz <patrick@lenz.sh>] - -* HABTM finders shouldn't return readonly records. #2525 [Patrick Lenz <patrick@lenz.sh>] - -* Make all tests runnable on their own. #2521. [Blair Zajac <blair@orcaware.com>] - - -*1.12.1* (October 19th, 2005) - -* Always parenthesize :conditions options so they may be safely combined with STI and constraints. - -* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com] - -* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations - - -*1.12.0* (October 16th, 2005) - -* Update/clean up documentation (rdoc) - -* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 [Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>] - -* Change default logging colors to work on both white and black backgrounds. [Sam Stephenson] - -* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 [purestorm@ggnore.net] - -* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 [Robby Russell <robby@planetargon.com>] - -* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. - -* Avoid memleak in dev mode when using fcgi - -* Simplified .clear on active record associations by using the existing delete_records method. #1906 [Caleb <me@cpb.ca>] - -* Delegate access to a customized primary key to the conventional id method. #2444. [Blair Zajac <blair@orcaware.com>] - -* Fix errors caused by assigning a has-one or belongs-to property to itself - -* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped [Sam Stephenson] - -* Update DB2 adapter. #2206. [contact@maik-schmidt.de] - -* Corrections to SQLServer native data types. #2267. [rails.20.clarry@spamgourmet.com] - -* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. - -* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. [Blair Zajac <blair@orcaware.com>] - -* Misc doc fixes (typos/grammar/etc.). #2430. [coffee2code] - -* Add test coverage for content_columns. #2432. [coffee2code] - -* Speed up for unthreaded environments. #2431. [Stefan Kaes] - -* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. [Stefan Kaes] - -* Speed up the setting of table_name. #2428. [Stefan Kaes] - -* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. [Stefan Kaes] - -* Fix typo of 'constrains' to 'contraints'. #2069. [Michael Schuerig <michael@schuerig.de>] - -* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. [Stefan Kaes] - -* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. [Michael Schuerig <michael@schuerig.de>] - -* Add geometric type for postgresql adapter. #2233 [Andrew Kaspick] - -* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. [Stefan Kaes] - -* Add convenience predicate methods on Column class. In partial fullfilment of #1236. [Stefan Kaes] - -* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 [Chad Fowler <chad@chadfowler.com>, Nicholas Seckar] - -* Added :force option to create_table that'll try to drop the table if it already exists before creating - -* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. [Nicholas Seckar] - -* Use foreign_key inflection uniformly. #2156 [Blair Zajac <blair@orcaware.com>] - -* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 [joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>] - -* Returning false from before_destroy should cancel the action. #1829 [Jeremy Huffman] - -* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 [mat <mat@absolight.fr>] - -* Extensive documentation for the abstract database adapter. #2250 [François Beausoleil <fbeausoleil@ftml.net>] - -* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 [jay@jay.fm, Blair Zajac <blair@orcaware.com>] - -* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 [Manuel Holtgrewe <purestorm@ggnore.net>] - -* Make update_attribute use the same writer method that update_attributes uses. - #2237 [trevor@protocool.com] - -* Make migrations honor table name prefixes and suffixes. #2298 [Jakob Skjerning, Marcel Molina Jr.] - -* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 [dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org] - -* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 [chris@chrisbrinker.com] - -* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) - -* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: - - ActiveRecord::Base.observers = :cacher, :garbage_collector - -* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 [solo@gatelys.com] - -* Wrap :conditions in parentheses to prevent problems with OR's #1871 [Jamis Buck] - -* Allow the postgresql adapter to work with the SchemaDumper. [Jamis Buck] - -* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. [Jamis Buck] - -* Fixed migrations for Windows when using more than 10 [David Naseby] - -* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 [Florian Weber] - -* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 [Tobias Lütke] - -* Improved migrations' behavior when the schema_info table is empty. [Nicholas Seckar] - -* Fixed that Observers didn't observe sub-classes #627 [Florian Weber] - -* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 [Marcel Molina Jr.] - -* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 [skae] - -* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 [Florian Weber] - -* Added better exception error when unknown column types are used with migrations #1814 [François Beausoleil] - -* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 [kajism@yahoo.com] - -* Fixed comparison of Active Record objects so two new objects are not equal #2099 [deberg] - -* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 [Tom Ward] - -* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 [coffee2code] - -* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 [sd@notso.net] - -* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ - -* Make sure the schema_info table is created before querying the current version #1903 - -* Fixtures ignore table name prefix and suffix #1987 [Jakob Skjerning] - -* Add documentation for index_type argument to add_index method for migrations #2005 [Blaine] - -* Modify read_attribute to allow a symbol argument #2024 [Ken Kunz] - -* Make destroy return self #1913 [Sebastian Kanthak] - -* Fix typo in validations documentation #1938 [court3nay] - -* Make acts_as_list work for insert_at(1) #1966 [hensleyl@papermountain.org] - -* Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky] - -* Allow add_column and create_table to specify NOT NULL #1712 [emptysands@gmail.com] - -* Fix create_table so that id column is implicitly added [Rick Olson] - -* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 - -* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 - -* Fixed the handling of camelCase columns names in Oracle #1798 - -* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 - -* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 - -* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 [Tobias Lütke] - - class Comment < AR:B - def self.search(q) - find(:all, :conditions => ["body = ?", q]) - end - end - - class Post < AR:B - has_many :comments - end - - Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' - - NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as - by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on - details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself - noticed :) - -* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 [Sam Stephenson] - -* Remove extra definition of supports_migrations? from abstract_adaptor.rb [Nicholas Seckar] - -* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions - -* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 [Maik Schmidt] - -* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 [Stefan Kaes] - - -*1.11.1* (11 July, 2005) - -* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 [Rick Olson] - -* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 [tyler@kianta.com] - -* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 [Sam Stephenson] - -* Correct reflected table name for singular associations. #1688 [court3nay] - -* Fixed optimistic locking with SQL Server #1660 [tom@popdog.net] - -* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current - -* Added better error message for "packets out of order" #1630 [court3nay] - -* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 - - -*1.11.0* (6 July, 2005) - -* Fixed that Yaml error message in fixtures hid the real error #1623 [Nicholas Seckar] - -* Changed logging of SQL statements to use the DEBUG level instead of INFO - -* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. - -* Added callback hooks to association collections #1549 [Florian Weber]. Example: - - class Project - has_and_belongs_to_many :developers, :before_add => :evaluate_velocity - - def evaluate_velocity(developer) - ... - end - end - - ..raising an exception will cause the object not to be added (or removed, with before_remove). - - -* Fixed Base.content_columns call for SQL Server adapter #1450 [DeLynn Berry] - -* Fixed Base#write_attribute to work with both symbols and strings #1190 [Paul Legato] - -* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 [Florian Weber] - -* Speed up ActiveRecord#method_missing for the common case (read_attribute). - -* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 [Stefan Kaes] - -* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 [Chris McGrath] - -* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 [raidel@onemail.at] - -* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 [Michael Schuerig] - -* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 [DeLynn Berry] - -* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 [Mark Imbriaco/DeLynn Berry] - -* Fixed that multiparameter posts ignored attr_protected #1532 [alec+rails@veryclever.net] - -* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 [flash@vanklinkenbergsoftware.nl] - -* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: - - Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' - - ...should instead be: - - Developer.find( - :all, - :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', - :conditions => 'project_id=1' - ) - -* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 [Marcel Molina Jr.] - -* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 [cluon] - -* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 - -* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 [Alisdair McDiarmid] - -* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice - -* Allow any Enumerable, not just Array, to work as bind variables #1344 [Jeremy Kemper] - -* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. - Example: - - david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] - david.save - - If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new - project is saved when david.save is called. - - Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: - - david.project_ids = [1, 5, 7] - -* Corrected typo in find SQL for has_and_belongs_to_many. #1312 [ben@bensinclair.com] - -* Fixed sanitized conditions for has_many finder method. #1281 [jackc@hylesanderson.com, pragdave, Tobias Lütke] - -* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 [dave@cherryville.org] - -* Corrected @@configurations typo #1410 [david@ruppconsulting.com] - -* Return PostgreSQL columns in the order they were declared #1374 [perlguy@gmail.com] - -* Allow before/after update hooks to work on models using optimistic locking - -* Eager loading of dependent has_one associations won't delete the association #1212 - -* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. - -* Using transactional fixtures now causes the data to be loaded only once. - -* Added fixture accessor methods that can be used when instantiated fixtures are disabled. - - fixtures :web_sites - - def test_something - assert_equal "Ruby on Rails", web_sites(:rubyonrails).name - end - -* Added DoubleRenderError exception that'll be raised if render* is called twice #518 [Nicholas Seckar] - -* Fixed exceptions occuring after render has been called #1096 [Nicholas Seckar] - -* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 - -* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead - -* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: - - Conditional validations such as the following are made possible: - validates_numericality_of :income, :if => :employed? - - Conditional validations can also solve the salted login generator problem: - validates_confirmation_of :password, :if => :new_password? - - Using blocks: - validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } - -* Fixed use of construct_finder_sql when using :join #1288 [dwlt@dwlt.net] - -* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 [Rick Olson] - -* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 [Jeremy Kemper] - -* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. - -* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. - -* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: - - # SELECT * FROM topics WHERE title IN ('First', 'Second') - Topic.find_all_by_title(["First", "Second"]) - -* Added compatibility with camelCase column names for dynamic finders #533 [Dee Zsombor] - -* Fixed extraneous comma in count() function that made it not work with joins #1156 [Jarkko Laine/Dee Zsombor] - -* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 [Alisdair McDiarmid] - -* Fixed that validate_length_of lost :on option when :within was specified #1195 [jhosteny@mac.com] - -* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: - - development: - adapter: postgresql - database: rails_development - host: localhost - username: postgres - password: - encoding: UTF8 - min_messages: ERROR - -* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 [Jamis Buck] - -* Added validates_exclusion_of as a negative of validates_inclusion_of - -* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls - - -*1.10.1* (20th April, 2005) - -* Fixed frivilous database queries being triggered with eager loading on empty associations and other things - -* Fixed order of loading in eager associations - -* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 - - -*1.10.0* (19th April, 2005) - -* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: - - for post in Post.find(:all, :limit => 100) - puts "Post: " + post.title - puts "Written by: " + post.author.name - puts "Last comment on: " + post.comments.first.created_on - end - - This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: - - for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) - - ...and the number of database queries needed is now 1. - -* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: - - Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(:first, :order => "created_on DESC", :offset => 5) - Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) - Person.find(:all, :offset => 10, :limit => 10) - -* Added acts_as_nested_set #1000 [wschenk]. Introduction: - - This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with - the added feature that you can select the children and all of it's descendants with - a single query. A good use case for this is a threaded post system, where you want - to display every reply to a comment without multiple selects. - -* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid [Dave Thomas] - -* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 [gnuman1@gmail.com] - -* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 [andrew.john.peters@gmail.com] - -* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 [stephenh@chase3000.com] - -* Fixed page caching for non-vhost applications living underneath the root #1004 [Ben Schumacher] - -* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 [adelle] - -* Added the option to specify the acceptance string in validates_acceptance_of #1106 [caleb@aei-tech.com] - -* Added insert_at(position) to acts_as_list #1083 [DeLynnB] - -* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) - -* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 [yon@milliped.com] - -* Fixed boolean saving on Oracle #1093 [mparrish@pearware.org] - -* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 - -* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 [Leon Bredt] - -* Added quoting of column names for fixtures #997 [jcfischer@gmail.com] - -* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis] - -* Fixed that benchmarking times for rendering included db runtimes #987 [Stefan Kaes] - -* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org] - -* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 [Jeremy Kemper] - -* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 [dave@cherryville.org] - -* Fixed Base.silence/benchmark to only log if a logger has been configured #986 [Stefan Kaes] - -* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 [Stefan Kaes] - -* Fixed bug in Base#hash method that would treat records with the same string-based id as different [Dave Thomas] - -* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) - - -*1.9.1* (27th March, 2005) - -* Fixed that Active Record objects with float attribute could not be cloned #808 - -* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 [Nicholas Seckar] - -* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count - -* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 [Scott Barron] - -* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 [delynnb] - - -*1.9.0* (22th March, 2005) - -* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: - - Developer.find_all nil, 'id ASC', 5 # return the first five developers - Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward - - This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. - -* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 [Nicholas Seckar/Sam Stephenson] - -* Improved the performance of the OCI8 adapter for Oracle #723 [pilx/gjenkins] - -* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 [dave@cherryville.org] - -* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 [mindel] - -* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 [Alisdair McDiarmid] - -* Added the possibility of specifying fixtures in multiple calls #816 [kim@tinker.com] - -* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net] - -* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak] - -* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak] - -* Fixed that SQLite3 exceptions are caught and reported properly #823 [yerejm] - -* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself - -* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) - - -*1.8.0* (7th March, 2005) - -* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) - -* Added support for timestamp with time zone in PostgreSQL #560 [Scott Barron] - -* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: - - * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the - +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ - objects that should be inspected to determine which attributes triggered the errors. - * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. - You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. - -* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 [rodrigo k] - -* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 [Jeremy Kemper] - -* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: - - class Account < ActiveRecord::Base - has_one :credit_card, :dependent => true - end - class CreditCard < ActiveRecord::Base - belongs_to :account - end - - account.credit_card # => returns existing credit card, lets say id = 12 - account.credit_card = CreditCard.create("number" => "123") - account.save # => CC with id = 12 is destroyed - - -* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: - - Validates whether the value of the specified attribute is numeric by trying to convert it to - a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression - <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). - - class Person < ActiveRecord::Base - validates_numericality_of :value, :on => :create - end - - Configuration options: - * <tt>message</tt> - A custom error message (default is: "is not a number") - * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) - * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) - - -* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 [Scott Barron] - -* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) - -* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 [james@slashetc.com] - - -*1.7.0* (24th February, 2005) - -* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 [Jamis Buck] - -* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: - - 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple - and safe way of passing table-specific sequence information to the adapter.) - 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to - resort to some hacks to get data converted to Date or Time in Ruby. - If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the - hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. - This is nasty - but if you use Duck Typing you'll probably not care very much. - In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is - valid - too many databases use DATE for both. - Timezones and sub-second precision on timestamps are not supported. - 3. Default values that are functions (such as "SYSDATE") are not supported. This is a - restriction of the way active record supports default values. - 4. Referential integrity constraints are not fully supported. Under at least - some circumstances, active record appears to delete parent and child records out of - sequence and out of transaction scope. (Or this may just be a problem of test setup.) - - The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ - -* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 [YuriSchimke] - -* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 [yerejm] - -* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 [tonka] - -* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 [Nicholas Seckar] - -* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 [daniel@nightrunner.com] - -* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 [adelle@bullet.net.au] - -* Fixed that find_by_* would fail when column names had numbers #670 [demetrius] - -* Fixed the SQL Server adapter on a bunch of issues #667 [DeLynn] - - 1. Created a new columns method that is much cleaner. - 2. Corrected a problem with the select and select_all methods - that didn't account for the LIMIT clause being passed into raw SQL statements. - 3. Implemented the string_to_time method in order to create proper instances of the time class. - 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. - 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. - -* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 [lmarlow] - -* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: - - class Person < ActiveRecord::Base - validates_each :first_name, :last_name do |record, attr| - record.errors.add attr, 'starts with z.' if attr[0] == ?z - end - end - -* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 [Jeremy Kemper] - -* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: - - class Person < ActiveRecord::Base - validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } - end - -* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 [Tim Bates] - -* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: - - class Project < ActiveRecord::Base - primary_key "sysid" - table_name "XYZ_PROJECT" - inheritance_column { original_inheritance_column + "_id" } - end - -* Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu] - - -*1.6.0* (January 25th, 2005) - -* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. - -* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 - -* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. - -* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example - - people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } - Person.update(people.keys, people.values) - -* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 [Scott Baron] - -* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 [notahat] - -* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 [Demetrius] - -* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 [Jeremy Kemper] - -* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 [Eric Anderson] - -* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 [Eric Anderson] - -* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not - -* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription - -* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 [Demetrius] - -* Fixed that find_all would produce invalid sql when called sequentialy #490 [Scott Baron] - - -*1.5.1* (January 18th, 2005) - -* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 [Tim Bates] - -* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 [Pelle] - - -*1.5.0* (January 17th, 2005) - -* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 [Eric Hodel] - -* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: - - class Book < ActiveRecord::Base - has_many :pages - belongs_to :library - - validates_associated :pages, :library - end - -* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: - - == Unsaved objects and associations - - You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be - aware of, mostly involving the saving of associated objects. - - === One-to-one associations - - * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in - order to update their primary keys - except if the parent object is unsaved (new_record? == true). - * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment - is cancelled. - * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). - * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does - not save the parent either. - - === Collections - - * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object - (the owner of the collection) is not yet stored in the database. - * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. - * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). - * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. - -* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 [Tim Bates] - -* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 [Tim Bates] - -* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 [Tim Bates] - -* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 [Tim Bates] - -* Fixed binary support for PostgreSQL #444 [alex@byzantine.no] - -* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the - collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If - it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, - it'll take one less SELECT query if you use length. - -* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 [atyp.de] - -* Fixed that foreign keys named the same as the association would cause stack overflow #437 [Eric Anderson] - -* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 [Alexey] - -* Added Base#reload that reloads the attributes of an object from the database #422 [Andreas Schwarz] - -* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 [Jeremy Kemper] - -* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 [Matt Mower] - -* Added that Observers can use the observes class method instead of overwriting self.observed_class(). - - Before: - class ListSweeper < ActiveRecord::Base - def self.observed_class() [ List, Item ] - end - - After: - class ListSweeper < ActiveRecord::Base - observes List, Item - end - -* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is - -* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name - -* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. - - Before: topic.update_attribute(:approved, !approved?) - After : topic.toggle!(:approved) - -* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: - - page.views # => 1 - page.increment!(:views) # executes an UPDATE statement - page.views # => 2 - - page.increment(:views).increment!(:views) - page.views # => 4 - -* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. - - - - -*1.14.2* (April 9th, 2005) - -* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen] - - -*1.14.1* (April 6th, 2006) - -* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. [Nicholas Seckar] - -* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) [Lars Pind] - -* Enable Limit/Offset in Calculations (closes #4558) [lmarlow] - -* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) [Rick Olson] - -* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 [lagroue@free.fr] - -* Allow AR::Base#respond_to? to behave when @attributes is nil [Ryan Davis] - -* Support eager includes when going through a polymorphic has_many association. [Rick Olson] - -* Added support for eagerly including polymorphic has_one associations. (closes #4525) [Rick Olson] - - class Post < ActiveRecord::Base - has_one :tagging, :as => :taggable - end - - Post.find :all, :include => :tagging - -* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many [Rick Olson] - -* Added support for going through a polymorphic has_many association: (closes #4401) [Rick Olson] - - class PhotoCollection < ActiveRecord::Base - has_many :photos, :as => :photographic - belongs_to :firm - end - - class Firm < ActiveRecord::Base - has_many :photo_collections - has_many :photos, :through => :photo_collections - end - -* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. [ruben.nine@gmail.com] - -* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. [Florian Weber] - -* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) [Stefan] - -* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) [Rick Olson] - -* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model [David Heinemeier Hansson] - -* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) [David Heinemeier Hansson] - -* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). [Marcel Mollina Jr.] - -* Fixed broken OCIAdapter #4457 [Michael Schoen] - - -*1.14.0* (March 27th, 2006) - -* Replace 'rescue Object' with a finer grained rescue. Closes #4431. [Nicholas Seckar] - -* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table [Rick Olson] - -* Add support for :include to with_scope [andrew@redlinesoftware.com] - -* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 [Michael Schoen] - -* Change periods (.) in table aliases to _'s. Closes #4251 [jeff@ministrycentered.com] - -* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 [Rick Olson] - -* Fixed issue that kept :select options from being scoped [Rick Olson] - -* Fixed db_schema_import when binary types are present #3101 [David Heinemeier Hansson] - -* Fixed that MySQL enums should always be returned as strings #3501 [David Heinemeier Hansson] - -* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. [Rick Olson] - - class Connection < ActiveRecord::Base - belongs_to :user - belongs_to :channel - end - - class Channel < ActiveRecord::Base - has_many :connections - has_many :contacts, :through => :connections, :class_name => 'User' # OLD - has_many :contacts, :through => :connections, :source => :user # NEW - end - -* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 [contact@maik-schmidt.de] - -* Allow overriding of find parameters in scoped has_many :through calls [Rick Olson] - - In this example, :include => false disables the default eager association from loading. :select changes the standard - select clause. :joins specifies a join that is added to the end of the has_many :through query. - - class Post < ActiveRecord::Base - has_many :tags, :through => :taggings, :include => :tagging do - def add_joins_and_select - find :all, :select => 'tags.*, authors.id as author_id', :include => false, - :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' - end - end - end - -* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson] - -* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney] - -* Quit ignoring default :include options in has_many :through calls [Mark James] - -* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) [Jonathan Viney] - -* Eager Loading support added for has_many :through => :has_many associations (see below). [Rick Olson] - -* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: - - class Firm < ActiveRecord::Base - has_many :clients - has_many :invoices, :through => :clients - end - - class Client < ActiveRecord::Base - belongs_to :firm - has_many :invoices - end - - class Invoice < ActiveRecord::Base - belongs_to :client - end - -* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) [Josh Susser] - -* Fixed has_many :through to include :conditions set on the :through association. closes #4020 [Jonathan Viney] - -* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) [andylien@gmail.com / Rick Olson] - -* SQL Server adapter gets some love #4298 [Ryan Tomayko] - -* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 [derrickspell@cdmplus.com] - -* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): - - Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') - -* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. [Rick Olson] - -* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 [Michael Koziarski] - -* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 [Michael Koziarski] - -* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 [Tom Ward] - -* Fixed that Migration#execute would have the table name prefix appended to its query #4110 [mark.imbriaco@pobox.com] - -* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) [Jamis Buck] - -* Use association's :conditions when eager loading. [Jeremy Evans] #4144 - -* Alias the has_and_belongs_to_many join table on eager includes. #4106 [Jeremy Evans] - - This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. - - Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') - -* Oracle adapter gets some love #4230 [Michael Schoen] - - * Changes :text to CLOB rather than BLOB [Moses Hohman] - * Fixes an issue with nil numeric length/scales (several) - * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] - * Tweaks a unit test to get it all green again - * Adds support for #current_database - -* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 [Rick Olson] - - class CachedModel < ActiveRecord::Base - self.abstract_class = true - end - - class Post < CachedModel - end - - CachedModel.abstract_class? - => true - - Post.abstract_class? - => false - - Post.base_class - => Post - - Post.table_name - => 'posts' - -* Allow :dependent options to be used with polymorphic joins. #3820 [Rick Olson] - - class Foo < ActiveRecord::Base - has_many :attachments, :as => :attachable, :dependent => :delete_all - end - -* Nicer error message on has_many :through when :through reflection can not be found. #4042 [court3nay] - -* Upgrade to Transaction::Simple 1.3 [Jamis Buck] - -* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model [Rick Olson] - -* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com] - -* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 [johan@johansorensen.com] - -* Dynamically set allow_concurrency. #4044 [Stefan Kaes] - -* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: - - topic.to_xml - - ...returns: - - <?xml version="1.0" encoding="UTF-8"?> - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <id type="integer">1</id> - <approved type="boolean">false</approved> - <replies-count type="integer">0</replies-count> - <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> - <written-on type="datetime">2003-07-16 09:28:00</written-on> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - ...and you can configure with: - - topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) - - ...that'll return: - - <topic> - <title>The First Topic</title> - <author-name>David</author-name> - <approved type="boolean">false</approved> - <content>Have a nice day</content> - <author-email-address>david@loudthinking.com</author-email-address> - <parent-id></parent-id> - <last-read type="date">2004-04-15</last-read> - </topic> - - You can even do load first-level associations as part of the document: - - firm.to_xml :include => [ :account, :clients ] - - ...that'll return something like: - - <?xml version="1.0" encoding="UTF-8"?> - <firm> - <id type="integer">1</id> - <rating type="integer">1</rating> - <name>37signals</name> - <clients> - <client> - <rating type="integer">1</rating> - <name>Summit</name> - </client> - <client> - <rating type="integer">1</rating> - <name>Microsoft</name> - </client> - </clients> - <account> - <id type="integer">1</id> - <credit-limit type="integer">50</credit-limit> - </account> - </firm> - -* Allow :counter_cache to take a column name for custom counter cache columns [Jamis Buck] - -* Documentation fixes for :dependent [robby@planetargon.com] - -* Stop the MySQL adapter crashing when views are present. #3782 [Jonathan Viney] - -* Don't classify the belongs_to class, it is already singular #4117 [keithm@infused.org] - -* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. [Rick Olson] - -* Fix quoting of inheritance column for STI eager loading #4098 [Jonathan Viney <jonathan@bluewire.net.nz>] - -* Added smarter table aliasing for eager associations for multiple self joins #3580 [Rick Olson] - - * The first time a table is referenced in a join, no alias is used. - * After that, the parent class name and the reflection name are used. - - Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... - - * Any additional join references get a numerical suffix like '_2', '_3', etc. - -* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. - -* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: - - # cascaded in two levels - >> Author.find(:all, :include=>{:posts=>:comments}) - => authors - +- posts - +- comments - - # cascaded in two levels and normal association - >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in two levels with two has_many associations - >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) - => authors - +- posts - +- comments - +- categorizations - - # cascaded in three levels - >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) - => companies - +- groups - +- members - +- favorites - -* Make counter cache work when replacing an association #3245 [eugenol@gmail.com] - -* Make migrations verbose [Jamis Buck] - -* Make counter_cache work with polymorphic belongs_to [Jamis Buck] - -* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 [anna@wota.jp] - -* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: - - * Does not support DATE SQL column types; use DATETIME instead. - * Date columns on HABTM join tables are returned as String, not Time. - * Insertions are potentially broken for :polymorphic join tables - * BLOB column access not yet fully supported - -* Clear stale, cached connections left behind by defunct threads. [Jeremy Kemper] - -* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. [Jeremy Kemper] - -* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 [Michael Schoen] - -* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 [David Heinemeier Hansson] - -* Speed up class -> connection caching and stale connection verification. #3979 [Stefan Kaes] - -* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. [Kevin Clark] - -* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 [dblack@wobblini.net] - -* Define attribute query methods to avoid method_missing calls. #3677 [Jonathan Viney] - -* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 [Simon Stapleton, Tom Ward] - -* Added support for nested scopes #3407 [anna@wota.jp]. Examples: - - Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 - - # inner rule is used. (all previous parameters are ignored) - Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') - end - - # parameters are merged - Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do - Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 - end - end - -* Fixed db2 connection with empty user_name and auth options #3622 [phurley@gmail.com] - -* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 [Masao Mutoh] - -* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 [Lars Pind] - -* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: - - Person.average :age - Person.minimum :age - Person.maximum :age - Person.sum :salary, :group => :last_name - -* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 [Luke Redpath] - -* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. [Jeremy Kemper] - -* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 [Aggregated by schoenm@earthlink.net] - -* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 [rubyonrails@atyp.de] - -* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [Stefan Kaes] - -* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva] - -* Allow :include to be used with has_many :through associations #3611 [Michael Schoen] - -* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 [Blair Zajac] - -* SQLServer: more compatible limit/offset emulation. #3779 [Tom Ward] - -* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 [Rick Olson] - -* PostgreSQL: correctly parse negative integer column defaults. #3776 [bellis@deepthought.org] - -* Fix problems with count when used with :include [Jeremy Hopple and Kevin Clark] - -* ActiveRecord::RecordInvalid now states which validations failed in its default error message [Tobias Lütke] - -* Using AssociationCollection#build with arrays of hashes should call build, not create [David Heinemeier Hansson] - -* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. [Nicholas Seckar] - -* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 [Maik Schmidt] - -* Support the :column option for remove_index with the PostgreSQL adapter. #3661 [Shugo Maeda] - -* Add documentation for add_index and remove_index. #3600 [Manfred Stienstra <m.stienstra@fngtps.com>] - -* If the OCI library is not available, raise an exception indicating as much. #3593 [Michael Schoen] - -* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. [Rick Olson] - -* Make dynamic finders honor additional passed in :conditions. #3569 [Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.] - -* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. [Nicholas Seckar] - -* Make .count work for has_many associations with multi line finder sql [Michael Schoen] - -* Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jamis Buck] - -* Allow configuration of the column used for optimistic locking [wilsonb@gmail.com] - -* Don't hardcode 'id' in acts as list. [ror@philippeapril.com] - -* Fix date errors for SQLServer in association tests. #3406 [Kevin Clark] - -* Escape database name in MySQL adapter when creating and dropping databases. #3409 [anna@wota.jp] - -* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 [alex.borovsky@gmail.com] - -* .with_scope imposed create parameters now bypass attr_protected [Tobias Lütke] - -* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. [Marcel Molina Jr.] - -* Multiple enhancements and adjustments to DB2 adaptor. #3377 [contact@maik-schmidt.de] - -* Sanitize scoped conditions. [Marcel Molina Jr.] - -* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) [David Heinemeier Hansson] - -* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. [Tobias Lütke] - -* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. [Tobias Lütke] - -* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 [yanowitz-rubyonrails@quantumfoam.org, Florian Weber] - -* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 [wejn@box.cz, Rick Olson, Scott Barron] - -* removed :piggyback in favor of just allowing :select on :through associations. [Tobias Lütke] - -* made method missing delegation to class methods on relation target work on :through associations. [Tobias Lütke] - -* made .find() work on :through relations. [Tobias Lütke] - -* Fix typo in association docs. #3296. [Blair Zajac] - -* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model [Tobias Lütke] - -*1.13.2* (December 13th, 2005) - -* Become part of Rails 1.0 - -* MySQL: allow encoding option for mysql.rb driver. [Jeremy Kemper] - -* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: - - class Post - has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author - end - - post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors - post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors - post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors - -* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson] - -* MySQL: fixes for the bundled mysql.rb driver. #3160 [Justin Forder] - -* SQLServer: fix obscure optimistic locking bug. #3068 [kajism@yahoo.com] - -* SQLServer: support uniqueidentifier columns. #2930 [keithm@infused.org] - -* SQLServer: cope with tables names qualified by owner. #3067 [jeff@ministrycentered.com] - -* SQLServer: cope with columns with "desc" in the name. #1950 [Ron Lusk, Ryan Tomayko] - -* SQLServer: cope with primary keys with "select" in the name. #3057 [rdifrango@captechventures.com] - -* Oracle: active? performs a select instead of a commit. #3133 [Michael Schoen] - -* MySQL: more robust test for nullified result hashes. #3124 [Stefan Kaes] - -* Reloading an instance refreshes its aggregations as well as its associations. #3024 [François Beausoleil] - -* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 [Paul Hammmond] - -* PostgreSQL: more robust sequence name discovery. #3087 [Rick Olson] - -* Oracle: use syntax compatible with Oracle 8. #3131 [Michael Schoen] - -* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. [Jeremy Kemper] - -* Added preliminary support for polymorphic associations [David Heinemeier Hansson] - -* Added preliminary support for join models [David Heinemeier Hansson] - -* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. [jeremy@jthopple.com, Marcel Molina Jr.] - -* Firebird: active? and reconnect! methods for handling stale connections. #428 [Ken Kunz <kennethkunz@gmail.com>] - -* Firebird: updated for FireRuby 0.4.0. #3009 [Ken Kunz <kennethkunz@gmail.com>] - -* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 [Jeremy Kemper] - -* Oracle: active? check pings the database rather than testing the last command status. #428 [Michael Schoen] - -* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 [kajism@yahoo.com] - -* Reloading a model doesn't lose track of its connection. #2996 [junk@miriamtech.com, Jeremy Kemper] - -* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 [colman@rominato.com, Florian Weber, Michael Schoen] - -* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 [Shugo Maeda] - -* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. [Jeremy Kemper] - -* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 [Shugo Maeda] - -* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. [Marcel Molina Jr.] - -* Correct boolean handling in generated reader methods. #2945 [Don Park, Stefan Kaes] - -* Don't generate read methods for columns whose names are not valid ruby method names. #2946 [Stefan Kaes] - -* Document :force option to create_table. #2921 [Blair Zajac <blair@orcaware.com>] - -* Don't add the same conditions twice in has_one finder sql. #2916 [Jeremy Evans] - -* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.] - -* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 [Ken Kunz <kennethkunz@gmail.com>] - -* SQLServer: active? and reconnect! methods for handling stale connections. #428 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 [MarkusQ@reality.com] - -* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 [kajism@yahoo.com, Tom Ward <tom@popdog.net>] - -* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 [Michael Schoen <schoenm@earthlink.net>] - -* Correct documentation for Base.delete_all. #1568 [Newhydra] - -* Oracle: test case for column default parsing. #2788 [Michael Schoen <schoenm@earthlink.net>] - -* Update documentation for Migrations. #2861 [Tom Werner <tom@cube6media.com>] - -* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 [Jeremy Kemper] - -* Oracle: Much faster column reflection. #2848 [Michael Schoen <schoenm@earthlink.net>] - -* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. [Jeremy Kemper] - -* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. [Jeremy Kemper] - -* PostgreSQL: correctly discover custom primary key sequences. #2594 [Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper] - -* SQLServer: don't report limits for unsupported field types. #2835 [Ryan Tomayko] - -* Include the Enumerable module in ActiveRecord::Errors. [Rick Bradley <rick@rickbradley.com>] - -* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 [rubyonrails@atyp.de] - -* Don't cast nil or empty strings to a dummy date. #2789 [Rick Bradley <rick@rickbradley.com>] - -* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 [rephorm@rephorm.com] - -* Fix sqlite adaptor's detection of missing dbfile or database declaration. [Nicholas Seckar] - -* Fixed acts_as_list for definitions without an explicit :order #2803 [Jonathan Viney] - -* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. [tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper] - -* Correct handling of complex order clauses with SQL Server limit emulation. #2770 [Tom Ward <tom@popdog.net>, Matt B.] - -* Correct whitespace problem in Oracle default column value parsing. #2788 [rick@rickbradley.com] - -* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 [larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper] - -* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. [Jeremy Kemper] - -* More compatible Oracle column reflection. #2771 [Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>] - - -*1.13.0* (November 7th, 2005) - -* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 [Ryan Tomayko] - -* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: - - has_many :posts, :include => [ :author, :comments ] - -* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: - - Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do - # Find where name = ? and active=true - Comment.find :all, :conditions => ['name = ?', name] - # Create comment associated with :post_id - Comment.create :body => "Hello world" - end - -* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 [Ryan Tomayko] - -* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: - - Comment.constrain(:creation => { :post_id => 5 }) do - # Associated with :post_id - Comment.create :body => "Hello world" - end - - This is rarely used directly, but allows for find_or_create on associations. So you can do: - - # If the tag doesn't exist, a new one is created that's associated with the person - person.tags.find_or_create_by_name("Summer") - -* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: - - # No 'Summer' tag exists - Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") - - # Now the 'Summer' tag does exist - Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") - -* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: - - class Account < ActiveRecord::Base - has_many :people do - def find_or_create_by_name(name) - first_name, *last_name = name.split - last_name = last_name.join " " - - find_or_create_by_first_name_and_last_name(first_name, last_name) - end - end - end - - person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") - person.first_name # => "David" - person.last_name # => "Heinemeier Hansson" - - Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). - -* Omit internal dtproperties table from SQLServer table list. #2729 [Ryan Tomayko] - -* Quote column names in generated SQL. #2728 [Ryan Tomayko] - -* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 [Jeremy Kemper] - -* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). [Jeremy Kemper] - -* Correct fixture behavior when table name pluralization is off. #2719 [Rick Bradley <rick@rickbradley.com>] - -* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 [Dan Peterson] - -* Added migration support for Oracle #2647 [Michael Schoen] - -* Worked around that connection can't be reset if allow_concurrency is off. #2648 [Michael Schoen <schoenm@earthlink.net>] - -* Fixed SQL Server adapter to pass even more tests and do even better #2634 [Ryan Tomayko] - -* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 [Tom Ward] - -* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 [Tom Ward] - -* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 [dansketcher@gmail.com] - -* Constraints are cloned so they can't be inadvertently modified while they're -in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] - -* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 [duane.johnson@gmail.com] - -* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 [Michael Schoen] - -* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 [maik schmidt] - - -*1.12.2* (October 26th, 2005) - -* Allow symbols to rename columns when using SQLite adapter. #2531 [Kevin Clark] - -* Map Active Record time to SQL TIME. #2575, #2576 [Robby Russell <robby@planetargon.com>] - -* Clarify semantics of ActiveRecord::Base#respond_to? #2560 [Stefan Kaes] - -* Fixed Association#clear for associations which have not yet been accessed. #2524 [Patrick Lenz <patrick@lenz.sh>] - -* HABTM finders shouldn't return readonly records. #2525 [Patrick Lenz <patrick@lenz.sh>] - -* Make all tests runnable on their own. #2521. [Blair Zajac <blair@orcaware.com>] - - -*1.12.1* (October 19th, 2005) - -* Always parenthesize :conditions options so they may be safely combined with STI and constraints. - -* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com] - -* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations - - -*1.12.0* (October 16th, 2005) - -* Update/clean up documentation (rdoc) - -* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 [Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>] - -* Change default logging colors to work on both white and black backgrounds. [Sam Stephenson] - -* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 [purestorm@ggnore.net] - -* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 [Robby Russell <robby@planetargon.com>] - -* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. - -* Avoid memleak in dev mode when using fcgi - -* Simplified .clear on active record associations by using the existing delete_records method. #1906 [Caleb <me@cpb.ca>] - -* Delegate access to a customized primary key to the conventional id method. #2444. [Blair Zajac <blair@orcaware.com>] - -* Fix errors caused by assigning a has-one or belongs-to property to itself - -* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped [Sam Stephenson] - -* Update DB2 adapter. #2206. [contact@maik-schmidt.de] - -* Corrections to SQLServer native data types. #2267. [rails.20.clarry@spamgourmet.com] - -* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. - -* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. [Blair Zajac <blair@orcaware.com>] - -* Misc doc fixes (typos/grammar/etc.). #2430. [coffee2code] - -* Add test coverage for content_columns. #2432. [coffee2code] - -* Speed up for unthreaded environments. #2431. [Stefan Kaes] - -* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. [Stefan Kaes] - -* Speed up the setting of table_name. #2428. [Stefan Kaes] - -* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. [Stefan Kaes] - -* Fix typo of 'constrains' to 'contraints'. #2069. [Michael Schuerig <michael@schuerig.de>] - -* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. [Stefan Kaes] - -* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. [Michael Schuerig <michael@schuerig.de>] - -* Add geometric type for postgresql adapter. #2233 [Andrew Kaspick] - -* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. [Stefan Kaes] - -* Add convenience predicate methods on Column class. In partial fullfilment of #1236. [Stefan Kaes] - -* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 [Chad Fowler <chad@chadfowler.com>, Nicholas Seckar] - -* Added :force option to create_table that'll try to drop the table if it already exists before creating - -* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. [Nicholas Seckar] - -* Use foreign_key inflection uniformly. #2156 [Blair Zajac <blair@orcaware.com>] - -* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 [joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>] - -* Returning false from before_destroy should cancel the action. #1829 [Jeremy Huffman] - -* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 [mat <mat@absolight.fr>] - -* Extensive documentation for the abstract database adapter. #2250 [François Beausoleil <fbeausoleil@ftml.net>] - -* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 [jay@jay.fm, Blair Zajac <blair@orcaware.com>] - -* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 [Manuel Holtgrewe <purestorm@ggnore.net>] - -* Make update_attribute use the same writer method that update_attributes uses. - #2237 [trevor@protocool.com] - -* Make migrations honor table name prefixes and suffixes. #2298 [Jakob Skjerning, Marcel Molina Jr.] - -* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 [dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org] - -* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 [chris@chrisbrinker.com] - -* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) - -* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: - - ActiveRecord::Base.observers = :cacher, :garbage_collector - -* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 [solo@gatelys.com] - -* Wrap :conditions in parentheses to prevent problems with OR's #1871 [Jamis Buck] - -* Allow the postgresql adapter to work with the SchemaDumper. [Jamis Buck] - -* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. [Jamis Buck] - -* Fixed migrations for Windows when using more than 10 [David Naseby] - -* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 [Florian Weber] - -* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 [Tobias Lütke] - -* Improved migrations' behavior when the schema_info table is empty. [Nicholas Seckar] - -* Fixed that Observers didn't observe sub-classes #627 [Florian Weber] - -* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 [Marcel Molina Jr.] - -* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 [skae] - -* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 [Florian Weber] - -* Added better exception error when unknown column types are used with migrations #1814 [François Beausoleil] - -* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 [kajism@yahoo.com] - -* Fixed comparison of Active Record objects so two new objects are not equal #2099 [deberg] - -* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 [Tom Ward] - -* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 [coffee2code] - -* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 [sd@notso.net] - -* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ - -* Make sure the schema_info table is created before querying the current version #1903 - -* Fixtures ignore table name prefix and suffix #1987 [Jakob Skjerning] - -* Add documentation for index_type argument to add_index method for migrations #2005 [Blaine] - -* Modify read_attribute to allow a symbol argument #2024 [Ken Kunz] - -* Make destroy return self #1913 [Sebastian Kanthak] - -* Fix typo in validations documentation #1938 [court3nay] - -* Make acts_as_list work for insert_at(1) #1966 [hensleyl@papermountain.org] - -* Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky] - -* Allow add_column and create_table to specify NOT NULL #1712 [emptysands@gmail.com] - -* Fix create_table so that id column is implicitly added [Rick Olson] - -* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 - -* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 - -* Fixed the handling of camelCase columns names in Oracle #1798 - -* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 - -* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 - -* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 [Tobias Lütke] - - class Comment < AR:B - def self.search(q) - find(:all, :conditions => ["body = ?", q]) - end - end - - class Post < AR:B - has_many :comments - end - - Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' - - NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as - by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on - details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself - noticed :) - -* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 [Sam Stephenson] - -* Remove extra definition of supports_migrations? from abstract_adaptor.rb [Nicholas Seckar] - -* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions - -* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 [Maik Schmidt] - -* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 [Stefan Kaes] - - -*1.11.1* (11 July, 2005) - -* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 [Rick Olson] - -* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 [tyler@kianta.com] - -* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 [Sam Stephenson] - -* Correct reflected table name for singular associations. #1688 [court3nay] - -* Fixed optimistic locking with SQL Server #1660 [tom@popdog.net] - -* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current - -* Added better error message for "packets out of order" #1630 [court3nay] - -* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 - - -*1.11.0* (6 July, 2005) - -* Fixed that Yaml error message in fixtures hid the real error #1623 [Nicholas Seckar] - -* Changed logging of SQL statements to use the DEBUG level instead of INFO - -* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. - -* Added callback hooks to association collections #1549 [Florian Weber]. Example: - - class Project - has_and_belongs_to_many :developers, :before_add => :evaluate_velocity - - def evaluate_velocity(developer) - ... - end - end - - ..raising an exception will cause the object not to be added (or removed, with before_remove). - - -* Fixed Base.content_columns call for SQL Server adapter #1450 [DeLynn Berry] - -* Fixed Base#write_attribute to work with both symbols and strings #1190 [Paul Legato] - -* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 [Florian Weber] - -* Speed up ActiveRecord#method_missing for the common case (read_attribute). - -* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 [Stefan Kaes] - -* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 [Chris McGrath] - -* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 [raidel@onemail.at] - -* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 [Michael Schuerig] - -* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 [DeLynn Berry] - -* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 [Mark Imbriaco/DeLynn Berry] - -* Fixed that multiparameter posts ignored attr_protected #1532 [alec+rails@veryclever.net] - -* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 [flash@vanklinkenbergsoftware.nl] - -* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: - - Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' - - ...should instead be: - - Developer.find( - :all, - :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', - :conditions => 'project_id=1' - ) - -* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 [Marcel Molina Jr.] - -* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 [cluon] - -* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 - -* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 [Alisdair McDiarmid] - -* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice - -* Allow any Enumerable, not just Array, to work as bind variables #1344 [Jeremy Kemper] - -* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. - Example: - - david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] - david.save - - If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new - project is saved when david.save is called. - - Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: - - david.project_ids = [1, 5, 7] - -* Corrected typo in find SQL for has_and_belongs_to_many. #1312 [ben@bensinclair.com] - -* Fixed sanitized conditions for has_many finder method. #1281 [jackc@hylesanderson.com, pragdave, Tobias Lütke] - -* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 [dave@cherryville.org] - -* Corrected @@configurations typo #1410 [david@ruppconsulting.com] - -* Return PostgreSQL columns in the order they were declared #1374 [perlguy@gmail.com] - -* Allow before/after update hooks to work on models using optimistic locking - -* Eager loading of dependent has_one associations won't delete the association #1212 - -* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. - -* Using transactional fixtures now causes the data to be loaded only once. - -* Added fixture accessor methods that can be used when instantiated fixtures are disabled. - - fixtures :web_sites - - def test_something - assert_equal "Ruby on Rails", web_sites(:rubyonrails).name - end - -* Added DoubleRenderError exception that'll be raised if render* is called twice #518 [Nicholas Seckar] - -* Fixed exceptions occuring after render has been called #1096 [Nicholas Seckar] - -* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 - -* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead - -* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: - - Conditional validations such as the following are made possible: - validates_numericality_of :income, :if => :employed? - - Conditional validations can also solve the salted login generator problem: - validates_confirmation_of :password, :if => :new_password? - - Using blocks: - validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } - -* Fixed use of construct_finder_sql when using :join #1288 [dwlt@dwlt.net] - -* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 [Rick Olson] - -* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 [Jeremy Kemper] - -* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. - -* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. - -* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: - - # SELECT * FROM topics WHERE title IN ('First', 'Second') - Topic.find_all_by_title(["First", "Second"]) - -* Added compatibility with camelCase column names for dynamic finders #533 [Dee Zsombor] - -* Fixed extraneous comma in count() function that made it not work with joins #1156 [Jarkko Laine/Dee Zsombor] - -* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 [Alisdair McDiarmid] - -* Fixed that validate_length_of lost :on option when :within was specified #1195 [jhosteny@mac.com] - -* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: - - development: - adapter: postgresql - database: rails_development - host: localhost - username: postgres - password: - encoding: UTF8 - min_messages: ERROR - -* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 [Jamis Buck] - -* Added validates_exclusion_of as a negative of validates_inclusion_of - -* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls - - -*1.10.1* (20th April, 2005) - -* Fixed frivilous database queries being triggered with eager loading on empty associations and other things - -* Fixed order of loading in eager associations - -* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 - - -*1.10.0* (19th April, 2005) - -* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: - - for post in Post.find(:all, :limit => 100) - puts "Post: " + post.title - puts "Written by: " + post.author.name - puts "Last comment on: " + post.comments.first.created_on - end - - This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: - - for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) - - ...and the number of database queries needed is now 1. - -* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: - - Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") - Person.find(:first, :order => "created_on DESC", :offset => 5) - Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) - Person.find(:all, :offset => 10, :limit => 10) - -* Added acts_as_nested_set #1000 [wschenk]. Introduction: - - This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with - the added feature that you can select the children and all of it's descendants with - a single query. A good use case for this is a threaded post system, where you want - to display every reply to a comment without multiple selects. - -* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid [Dave Thomas] - -* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 [gnuman1@gmail.com] - -* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 [andrew.john.peters@gmail.com] - -* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 [stephenh@chase3000.com] - -* Fixed page caching for non-vhost applications living underneath the root #1004 [Ben Schumacher] - -* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 [adelle] - -* Added the option to specify the acceptance string in validates_acceptance_of #1106 [caleb@aei-tech.com] - -* Added insert_at(position) to acts_as_list #1083 [DeLynnB] - -* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) - -* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 [yon@milliped.com] - -* Fixed boolean saving on Oracle #1093 [mparrish@pearware.org] - -* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 - -* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 [Leon Bredt] - -* Added quoting of column names for fixtures #997 [jcfischer@gmail.com] - -* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis] - -* Fixed that benchmarking times for rendering included db runtimes #987 [Stefan Kaes] - -* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org] - -* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 [Jeremy Kemper] - -* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 [dave@cherryville.org] - -* Fixed Base.silence/benchmark to only log if a logger has been configured #986 [Stefan Kaes] - -* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 [Stefan Kaes] - -* Fixed bug in Base#hash method that would treat records with the same string-based id as different [Dave Thomas] - -* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) - - -*1.9.1* (27th March, 2005) - -* Fixed that Active Record objects with float attribute could not be cloned #808 - -* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 [Nicholas Seckar] - -* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count - -* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 [Scott Barron] - -* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 [delynnb] - - -*1.9.0* (22th March, 2005) - -* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: - - Developer.find_all nil, 'id ASC', 5 # return the first five developers - Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward - - This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. - -* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 [Nicholas Seckar/Sam Stephenson] - -* Improved the performance of the OCI8 adapter for Oracle #723 [pilx/gjenkins] - -* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 [dave@cherryville.org] - -* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 [mindel] - -* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 [Alisdair McDiarmid] - -* Added the possibility of specifying fixtures in multiple calls #816 [kim@tinker.com] - -* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net] - -* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak] - -* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak] - -* Fixed that SQLite3 exceptions are caught and reported properly #823 [yerejm] - -* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself - -* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) - - -*1.8.0* (7th March, 2005) - -* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) - -* Added support for timestamp with time zone in PostgreSQL #560 [Scott Barron] - -* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: - - * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the - +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ - objects that should be inspected to determine which attributes triggered the errors. - * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. - You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. - -* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 [rodrigo k] - -* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 [Jeremy Kemper] - -* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: - - class Account < ActiveRecord::Base - has_one :credit_card, :dependent => true - end - class CreditCard < ActiveRecord::Base - belongs_to :account - end - - account.credit_card # => returns existing credit card, lets say id = 12 - account.credit_card = CreditCard.create("number" => "123") - account.save # => CC with id = 12 is destroyed - - -* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: - - Validates whether the value of the specified attribute is numeric by trying to convert it to - a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression - <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). - - class Person < ActiveRecord::Base - validates_numericality_of :value, :on => :create - end - - Configuration options: - * <tt>message</tt> - A custom error message (default is: "is not a number") - * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) - * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) - - -* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 [Scott Barron] - -* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) - -* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 [james@slashetc.com] - - -*1.7.0* (24th February, 2005) - -* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 [Jamis Buck] - -* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: - - 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple - and safe way of passing table-specific sequence information to the adapter.) - 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to - resort to some hacks to get data converted to Date or Time in Ruby. - If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the - hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. - This is nasty - but if you use Duck Typing you'll probably not care very much. - In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is - valid - too many databases use DATE for both. - Timezones and sub-second precision on timestamps are not supported. - 3. Default values that are functions (such as "SYSDATE") are not supported. This is a - restriction of the way active record supports default values. - 4. Referential integrity constraints are not fully supported. Under at least - some circumstances, active record appears to delete parent and child records out of - sequence and out of transaction scope. (Or this may just be a problem of test setup.) - - The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ - -* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 [YuriSchimke] - -* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 [yerejm] - -* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 [tonka] - -* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 [Nicholas Seckar] - -* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 [daniel@nightrunner.com] - -* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 [adelle@bullet.net.au] - -* Fixed that find_by_* would fail when column names had numbers #670 [demetrius] - -* Fixed the SQL Server adapter on a bunch of issues #667 [DeLynn] - - 1. Created a new columns method that is much cleaner. - 2. Corrected a problem with the select and select_all methods - that didn't account for the LIMIT clause being passed into raw SQL statements. - 3. Implemented the string_to_time method in order to create proper instances of the time class. - 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. - 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. - -* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 [lmarlow] - -* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: - - class Person < ActiveRecord::Base - validates_each :first_name, :last_name do |record, attr| - record.errors.add attr, 'starts with z.' if attr[0] == ?z - end - end - -* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 [Jeremy Kemper] - -* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: - - class Person < ActiveRecord::Base - validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } - end - -* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 [Tim Bates] - -* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: - - class Project < ActiveRecord::Base - primary_key "sysid" - table_name "XYZ_PROJECT" - inheritance_column { original_inheritance_column + "_id" } - end - -* Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu] - - -*1.6.0* (January 25th, 2005) - -* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. - -* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 - -* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. - -* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example - - people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } - Person.update(people.keys, people.values) - -* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 [Scott Baron] - -* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 [notahat] - -* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 [Demetrius] - -* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 [Jeremy Kemper] - -* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 [Eric Anderson] - -* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 [Eric Anderson] - -* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not - -* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription - -* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 [Demetrius] - -* Fixed that find_all would produce invalid sql when called sequentialy #490 [Scott Baron] - - -*1.5.1* (January 18th, 2005) - -* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 [Tim Bates] - -* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 [Pelle] - - -*1.5.0* (January 17th, 2005) - -* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 [Eric Hodel] - -* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: - - class Book < ActiveRecord::Base - has_many :pages - belongs_to :library - - validates_associated :pages, :library - end - -* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: - - == Unsaved objects and associations - - You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be - aware of, mostly involving the saving of associated objects. - - === One-to-one associations - - * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in - order to update their primary keys - except if the parent object is unsaved (new_record? == true). - * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment - is cancelled. - * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). - * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does - not save the parent either. - - === Collections - - * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object - (the owner of the collection) is not yet stored in the database. - * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. - * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). - * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. - -* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 [Tim Bates] - -* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 [Tim Bates] - -* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 [Tim Bates] - -* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 [Tim Bates] - -* Fixed binary support for PostgreSQL #444 [alex@byzantine.no] - -* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the - collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If - it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, - it'll take one less SELECT query if you use length. - -* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 [atyp.de] - -* Fixed that foreign keys named the same as the association would cause stack overflow #437 [Eric Anderson] - -* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 [Alexey] - -* Added Base#reload that reloads the attributes of an object from the database #422 [Andreas Schwarz] - -* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 [Jeremy Kemper] - -* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 [Matt Mower] - -* Added that Observers can use the observes class method instead of overwriting self.observed_class(). - - Before: - class ListSweeper < ActiveRecord::Base - def self.observed_class() [ List, Item ] - end - - After: - class ListSweeper < ActiveRecord::Base - observes List, Item - end - -* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is - -* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name - -* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. - - Before: topic.update_attribute(:approved, !approved?) - After : topic.toggle!(:approved) - -* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: - - page.views # => 1 - page.increment!(:views) # executes an UPDATE statement - page.views # => 2 - - page.increment(:views).increment!(:views) - page.views # => 4 - -* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. - - -*1.4.0* (January 4th, 2005) - -* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the - record increments the lock_version column and the locking facilities ensure that records instantiated twice - will let the last one saved raise a StaleObjectError if the first was also updated. Example: - - p1 = Person.find(1) - p2 = Person.find(1) - - p1.first_name = "Michael" - p1.save - - p2.first_name = "should fail" - p2.save # Raises a ActiveRecord::StaleObjectError - - You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, - or otherwise apply the business logic needed to resolve the conflict. - - #384 [Michael Koziarski] - -* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL. - They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, - Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do - <tt>Person.find_by_user_name(user_name)</tt>. - - It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like - <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing - <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do - <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. - - While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like - <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful, - though, as it's not possible to specify the order in which the objects are returned. - -* Added block-style for callbacks #332 [Jeremy Kemper]. - - Before: - before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" }) - - After: - before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" } - -* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 [Josh Peek] - -* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates - and times from the database. This is set to :local by default. - -* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite. - -* Added the possibility of having objects with acts_as_list created before their scope is available or... - -* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 [Maik Schmidt] - -* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 [DeLynn Barry] - -* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 [Jeremy Kemper] - -* Added HasManyAssociation#count that works like Base#count #413 [intinig] - -* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 [xal] - -* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 [Tobias Lütke] - -* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it. - If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 [Jeremy Kemper] - -* Fixed broken transactions that were actually only running object-level and not db level transactions [andreas] - -* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406 - -* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391 - -* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 [Dmitry V. Sabanin] - - -*1.3.0* (December 23, 2004) - -* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like: - - before: - require_association 'person' - class Employee < Person - end - - after: - class Employee < Person - end - - This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes. - -* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341 - -* Added scope option to validation_uniqueness #349 [Kent Sibilev] - -* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type. - This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100". - -* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil [what-a-day] - -* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case. - This only works for auto-incrementing primary keys called "id" for now #359 [Scott Baron] - -* Added Base#clear_association_cache to empty all the cached associations #347 [Tobias Lütke] - -* Added more informative exceptions in establish_connection #356 [Jeremy Kemper] - -* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise). - - Before: - person.attributes = @params["person"] - person.save - - Now: - person.update_attributes(@params["person"]) - -* Added Base.destroy and Base.delete to remove records without holding a reference to them first. - -* Added that query benchmarking will only happen if its going to be logged anyway #344 - -* Added higher_item and lower_item as public methods for acts_as_list #342 [Tobias Lütke] - -* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 [Jeremy Kemper] - -* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used - the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). [Marten] - -* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins [Anna Lissa Cruz] - -* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction. - If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction - bubble up even when you've dealt with local issues. Closes #231 and #340. - -* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 [dpiddy@gmail.com] - -* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations. - -* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request. - - - -*1.2.0* - -* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable - object. [what-a-day] - - class Person < ActiveRecord::Base - validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!" - validates_inclusion_of :age, :in=>0..99 - end - -* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example: - - class TodoItem < ActiveRecord::Base - acts_as_list :scope => :todo_list_id - belongs_to :todo_list - end - -* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in - categories and the likes. [Tobias Lütke] - -* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names - created_at/created_on or updated_at/updated_on are present. [Tobias Lütke] - -* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place [Tobias Lütke] - -* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all - -* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 [Marten] - -* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere [RedTerror] - -* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example: - - ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'. - This error is raised because the column 'type' is reserved for storing the class in case of inheritance. - Please rename this column if you didn't intend it to be used for storing the inheritance class or - overwrite Company.inheritance_column to use another column for that information. - -* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't - have any magic side effects. - -* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 [mjobin] - -* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples: - - Before: - errors.add(:name, "must be shorter") if name.size > 10 - errors.on(:name) # => "must be shorter" - errors.on("name") # => nil - - After: - errors.add(:name, "must be shorter") if name.size > 10 - errors.on(:name) # => "must be shorter" - errors.on("name") # => "must be shorter" - -* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching - it against the regular expression provided. [Marcel Molina Jr.] - - class Person < ActiveRecord::Base - validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create - end - -* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example: - - Validates that the specified attribute matches the length restrictions supplied in either: - - - configuration[:minimum] - - configuration[:maximum] - - configuration[:is] - - configuration[:within] (aka. configuration[:in]) - - Only one option can be used at a time. - - class Person < ActiveRecord::Base - validates_length_of :first_name, :maximum=>30 - validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind" - validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name" - validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character" - validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me." - end - -* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself. - -* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system. - Useful for making sure that only one user can be named "davidhh". - - class Person < ActiveRecord::Base - validates_uniqueness_of :user_name - end - - When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified - attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. - - -* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example: - - Model: - class Person < ActiveRecord::Base - validates_confirmation_of :password - end - - View: - <%= password_field "person", "password" %> - <%= password_field "person", "password_confirmation" %> - - The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual. - It exists only as an in-memory variable for validating the password. This check is performed both on create and update. - - -* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example: - - class Person < ActiveRecord::Base - validates_acceptance_of :terms_of_service - end - - The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update. - - NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox. - - -* Added validation macros to make the stackable just like the life cycle callbacks. Examples: - - class Person < ActiveRecord::Base - validate { |record| record.errors.add("name", "too short") unless name.size > 10 } - validate { |record| record.errors.add("name", "too long") unless name.size < 20 } - validate_on_create :validate_password - - private - def validate_password - errors.add("password", "too short") unless password.size > 6 - end - end - -* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples: - - Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20] - Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date] - -* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening - through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer - columns. - -* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient - [Florian Weber] - -* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation: - - <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is - specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM. - -* Fixed that methods wrapped in callbacks still return their original result #260 [Jeremy Kemper] - -* Fixed the Inflector to handle the movie/movies pair correctly #261 [Scott Baron] - -* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example: - - Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }]) - -* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method [Michael Koziarski] - - Before: - find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])] - find_first([ "firm_id = %s", firm_id ])] # unsafe! - - After: - find_first([ "user_name = ? AND password = ?", user_name, password ])] - find_first([ "firm_id = ?", firm_id ])] - -* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information) - -* Fixed fixtures using primary key fields called something else than "id" [dave] - -* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 [HariSeldon] - -* Added reverse order of deleting fixtures, so referential keys can be maintained #247 [Tim Bates] - -* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 [Jeremy Kemper] - -* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable - -* Fixed problems with primary keys and postgresql sequences (#230) [Tim Bates] - -* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development. - This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments. - - NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through - require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the - auto-loading associations. - -* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like: - - david: - id: 1 - name: David - - jamis: - id: 2 - name: Jamis - - <% for digit in 3..10 %> - dev_<%= digit %>: - id: <%= digit %> - name: fixture_<%= digit %> - <% end %> - -* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like: - - fixtures/developers/fixtures.yaml - fixtures/accounts/fixtures.yaml - - ...you now need to do: - - fixtures/developers.yaml - fixtures/accounts.yaml - -* Changed the fixture format from: - - name: david - data: - id: 1 - name: David Heinemeier Hansson - birthday: 1979-10-15 - profession: Systems development - --- - name: steve - data: - id: 2 - name: Steve Ross Kellock - birthday: 1974-09-27 - profession: guy with keyboard - - ...to: - - david: - id: 1 - name: David Heinemeier Hansson - birthday: 1979-10-15 - profession: Systems development - - steve: - id: 2 - name: Steve Ross Kellock - birthday: 1974-09-27 - profession: guy with keyboard - - The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten! - -* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements. - - -*1.1.0* (34) - -* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically - instantiated in instance variables relating to their names using the following style: - - class FixturesTest < Test::Unit::TestCase - fixtures :developers # you can add more with comma separation - - def test_developers - assert_equal 3, @developers.size # the container for all the fixtures is automatically set - assert_kind_of Developer, @david # works like @developers["david"].find - assert_equal "David Heinemeier Hansson", @david.name - end - end - -* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional - attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association - between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back - approach: - - post.categories.push_with_attributes(category, :added_on => Date.today) - post.categories.first.added_on # => Date.today - - NOTE: The categories table doesn't have a added_on column, it's the categories_post join table that does! - -* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations [Jeremy Kemper] - -* Fixed that database passwords couldn't be all numeric [Jeremy Kemper] - -* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly [Jeremy Kemper] - -* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all [Sam Stephenson/Jeremy Kemper] - -* Added that you can pass overlapping ids to find without getting duplicated records back [Jeremy Kemper] - -* Added that Base.benchmark returns the result of the block [Jeremy Kemper] - -* Fixed problem with unit tests on Windows with SQLite [paterno] - -* Fixed that quotes would break regular non-yaml fixtures [Dmitry Sabanin/daft] - -* Fixed fixtures on windows with line endings cause problems under unix / mac [Tobias Lütke] - -* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id - -* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations - -* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records [geech] - -* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete [geech] - -* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create [geech] - -* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works: - - [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] - -* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called - before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations. - -* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates, - which is common on associations that also use metadata. Usage: post.categories.uniq - -* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one - -* Fixed has_and_belongs_to_many to treat associations between classes in modules properly [Florian Weber] - -* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist [geech] - -* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues [geech] - -* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods [geech] - -* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash [geech] - -* Added that any additional fields added to the join table in a has_and_belongs_to_many association - will be placed as attributes when pulling records out through has_and_belongs_to_many associations. - This is helpful when have information about the association itself that you want available on retrival. - -* Added better loading exception catching and RubyGems retries to the database adapters [alexeyv] - -* Fixed bug with per-model transactions [daniel] - -* Fixed Base#transaction so that it returns the result of the last expression in the transaction block [alexeyv] - -* Added Fixture#find to find the record corresponding to the fixture id. The record - class name is guessed by using Inflector#classify (also new) on the fixture directory name. - - Before: Document.find(@documents["first"]["id"]) - After : @documents["first"].find - -* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly [Andreas Schwarz] - -* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM [geech] - -* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete - adapters for a call to the dbm. [Andreas Schwarz] - -* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR. - - -*1.0.0 (35)* - -* Added OO-style associations methods [Florian Weber]. Examples: - - Project#milestones_count => Project#milestones.size - Project#build_to_milestones => Project#milestones.build - Project#create_for_milestones => Project#milestones.create - Project#find_in_milestones => Project#milestones.find - Project#find_all_in_milestones => Project#milestones.find_all - -* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated - serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this: - - class User < ActiveRecord::Base - serialize :settings - end - - This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify - an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in - the hierarchy. Example: - - class User < ActiveRecord::Base - serialize :settings, :class_name => "Hash" - end - - user = User.create("settings" => %w( one two three )) - User.find(user.id).settings # => raises SerializationTypeMismatch - -* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class - you want to have connected to another database than Base. This will automatically also connect decendents of that class - to the different database [Renald Buter]. - -* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks - can raise exceptions knowing that the save will be rolled back. [Suggested by Alexey Verkhovsky] - -* Added column name quoting so reserved words, such as "references", can be used as column names [Ryan Platte] - -* Added the possibility to chain the return of what happened inside a logged block [geech]: - - This now works: - log { ... }.map { ... } - - Instead of doing: - result = [] - log { result = ... } - result.map { ... } - -* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" [Anna Lissa Cruz] - -* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema, - person.respond_to? "name" will return true. - -* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block. - Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all): - - Project.benchmark("Creating project") do - project = Project.create("name" => "stuff") - project.create_manager("name" => "David") - project.milestones << Milestone.find_all - end - -* Added logging of invalid SQL statements [Daniel Von Fange] - -* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name [Andreas Schwarz] - -* Added RubyGems require attempt if sqlite-ruby is not available through regular methods. - -* Added compatibility with 2.x series of sqlite-ruby drivers. [Jamis Buck] - -* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to - assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on - mistaken association assignments. [Reported by Andreas Schwarz] - -* Added the option to keep many fixtures in one single YAML document [what-a-day] - -* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing - the type for inheritance hierarchies. [Dave Steinberg] - -* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten [Dave Steinberg] - -* Added the option to observer more than one class at the time by specifying observed_class as an array - -* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them - on PostgreSQL. [Dave Steinberg] - -* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49) - -* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port [Andreas Schwarz] - -* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue. - -* Changed class inheritable attributes to not use eval [Caio Chassot] - -* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those [Marcel Molina Jr.] - -* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) [Marcel Molina Jr.] - -* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed. - -* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter [Andreas Schwarz] - -* Fixed PostgreSQL defaults are now handled gracefully [Dave Steinberg] - -* Fixed increment/decrement_counter are now atomic updates [Andreas Schwarz] - -* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis [radsaq/Florian Gross] - -* Fixed that cloned records would point attribute references on the parent object [Andreas Schwarz] - -* Fixed SQL for type call on inheritance hierarchies [Caio Chassot] - -* Fixed bug with typed inheritance [Florian Weber] - -* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association - - -*0.9.5* - -* Expanded the table_name guessing rules immensely [Florian Green]. Documentation: - - Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending - directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used - to guess the table name from even when called on Reply. The guessing rules are as follows: - * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table. - * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies", - so a Category class becomes a categories table. - * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table. - * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table. - * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table. - * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table. - * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table. - * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table. - * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table. - * Class name ends in an "s": No additional characters are added or removed. - * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table. - * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table. - Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. - So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts". - - You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a - "mice" table. Example: - - class Mouse < ActiveRecord::Base - def self.table_name() "mice" end - end - - This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb. - -* Added find_all_in_collection to has_many defined collections. Works like this: - - class Firm < ActiveRecord::Base - has_many :clients - end - - firm.id # => 1 - firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000 - - [Requested by Dave Thomas] - -* Fixed finders for inheritance hierarchies deeper than one level [Florian Weber] - -* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this: - - class Person < ActiveRecord::Base - protected - def validation - errors.add_on_boundry_breaking "password", 3..20 - end - end - - This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if - the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings. - -* Implemented a clone method that works properly with AR. It returns a clone of the record that - hasn't been assigned an id yet and is treated as a new record. - -* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified [Scott Barron] - -* Fixed that bignums are saved properly instead of attempted to be YAMLized [Andreas Schwartz] - -* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec [Chad Fowler] - -* Fixed a bug with the exclusively_dependent option for has_many - - -*0.9.4* - -* Correctly guesses the primary key when the class is inside a module [Dave Steinberg]. - -* Added [] and []= as alternatives to read_attribute and write_attribute [Dave Steinberg] - -* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq]. - -* The ids passed to find and find_on_conditions are now automatically sanitized. - -* Added escaping of plings in YAML content. - -* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class. - -* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create) - - -*0.9.3* - -* Fixed bug with using a different primary key name together with has_and_belongs_to_many [Investigation by Scott] - -* Added :exclusively_dependent option to the has_many association macro. The doc reads: - - If set to true all the associated object are deleted in one SQL statement without having their - before_destroy callback run. This should only be used on associations that depend solely on - this class and don't need to do any clean-up in before_destroy. The upside is that it's much - faster, especially if there's a counter_cache involved. - -* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server - running on another port than the default. - -* Converted the new natural singleton methods that prevented AR objects from being saved by PStore - (and hence be placed in a Rails session) to a module. [Florian Weber] - -* Fixed the use of floats (was broken since 0.9.0+) - -* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with - Action Pack scaffolding. - -* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) [radsaq] - - -*0.9.2* - -* Added static method for instantly updating a record - -* Treat decimal and numeric as Ruby floats [Andreas Schwartz] - -* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too) - -* Removed debugging output accidently left in (which would screw web applications) - - -*0.9.1* - -* Added MIT license - -* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model: - - class Event < ActiveRecord::Base - has_one_and_belongs_to_many :sponsors - end - - class Sponsor < ActiveRecord::Base - has_one_and_belongs_to_many :sponsors - end - - Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class: - - roskilde_festival.add_to_sponsors(carlsberg) - roskilde_festival.remove_from_sponsors(carlsberg) - - nike.add_to_events(world_cup) - nike.remove_from_events(world_cup) - - Now you can use regular array-styled methods: - - roskilde_festival.sponsors << carlsberg - roskilde_festival.sponsors.delete(carlsberg) - - nike.events << world_cup - nike.events.delete(world_cup) - -* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging - object by setting the foreign key to null. Consider this model: - - class Post < ActiveRecord::Base - has_many :comments - end - - class Comment < ActiveRecord::Base - belongs_to :post - end - - You could do something like: - - funny_comment.has_post? # => true - announcement.comments.delete(funny_comment) - funny_comment.has_post? # => false - - -*0.9.0* - -* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications) - [Implementation idea by Michael Neumann, debugging assistance by Jamis Buck] - -* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute. - This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%. - Done by doing lazy type conversions and caching column information on the class-level. - -* Added callback objects and procs as options for implementing the target for callback macros. - -* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider: - - class Post < ActiveRecord::Base - has_many :comments - end - - class Comment < ActiveRecord::Base - belongs_to :post - end - - Iterating over 100 posts like this: - - <% for post in @posts %> - <%= post.title %> has <%= post.comments_count %> comments - <% end %> - - Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column - to the posts table and rewrite the comments association macro with: - - class Comment < ActiveRecord::Base - belongs_to :post, :counter_cache => true - end - - Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life - with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify - :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another), - you'll have to manage the counter yourself. - -* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model: - - class Project < ActiveRecord::Base - has_one :manager - end - - class Manager < ActiveRecord::Base - belongs_to :project - end - - Earlier, assignments would work like following regardless of which way the assignment told the best story: - - active_record.manager_id = david.id - - Now you can do it either from the belonging side: - - david.project = active_record - - ...or from the having side: - - active_record.manager = david - - If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the - project_id attribute on david would be set to the id of active_record, then david would be saved. - -* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model: - - class Project < ActiveRecord::Base - has_many :milestones - end - - class Milestone < ActiveRecord::Base - belongs_to :project - end - - Earlier, assignments would work like following regardless of which way the assignment told the best story: - - deadline.project_id = active_record.id - - Now you can do it either from the belonging side: - - deadline.project = active_record - - ...or from the having side: - - active_record.milestones << deadline - - The milestone is automatically saved with the new foreign key. - -* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using - to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time). - Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header. - This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do: - - user = User.find(1) - user.preferences = { "background" => "black", "display" => large } - user.save - - User.find(1).preferences # => { "background" => "black", "display" => large } - - Please note that this method should only be used when you don't care about representing the object in proper columns in - the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through - aggregations than this new option. - -* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash - directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement - new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this: - - class Song < ActiveRecord::Base - # Uses an integer of seconds to hold the length of the song - - def length=(minutes) - write_attribute("length", minutes * 60) - end - - def length - read_attribute("length") / 60 - end - end - - The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly. - This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think - you know what you're doing and aren't afraid of future consequences, this is an option. - -* Applied a few minor bug fixes reported by Daniel Von Fange. - - -*0.8.4* - -_Reflection_ - -* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations. - -* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects. - -* Added Base#attribute_names which returns an array of names for the attributes available on the object. - -* Added Base#column_for_attribute(name) which returns the column description object for the named attribute. - - -_Misc_ - -* Added multi-parameter assignment: - - # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done - # by calling new on the column type or aggregation type (through composed_of) object with these parameters. - # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate - # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the - # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float, - # s for String, and a for Array. - - This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day. - -* Fixed bug with custom primary key column name and Base.find on multiple parameters. - -* Fixed bug with dependent option on has_one associations if there was no associated object. - - -*0.8.3* - -_Transactions_ - -* Added transactional protection for destroy (important for the new :dependent option) [Suggested by Carl Youngblood] - -* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions) - -* Changed transactions so only exceptions will cause a rollback, not returned false. - - -_Mapping_ - -* Added support for non-integer primary keys [Aredridel/earlier work by Michael Neumann] - - User.find "jdoe" - Product.find "PDKEY-INT-12" - -* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either - be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key - of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id". - -* Added an overwriteable primary_key method that'll instruct AR to the name of the - id column [Aredridele/earlier work by Guan Yang] - - class Project < ActiveRecord::Base - def self.primary_key() "project_id" end - end - -* Fixed that Active Records can safely associate inside and out of modules. - - class MyApplication::Account < ActiveRecord::Base - has_many :clients # will look for MyApplication::Client - has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest - end - -* Fixed that Active Records can safely live inside modules [Aredridel] - - class MyApplication::Account < ActiveRecord::Base - end - - -_Misc_ - -* Added freeze call to value object assignments to ensure they remain immutable [Spotted by Gavin Sinclair] - -* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is - observed_class() class method. This is more consistant with things like self.table_name(). Works like this: - - class AuditObserver < ActiveRecord::Observer - def self.observed_class() Account end - def after_update(account) - AuditTrail.new(account, "UPDATED") - end - end - - [Suggested by Gavin Sinclair] - -* Create new Active Record objects by setting the attributes through a block. Like this: - - person = Person.new do |p| - p.name = 'Freddy' - p.age = 19 - end - - [Suggested by Gavin Sinclair] - - -*0.8.2* - -* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are - run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback - method: - - class Topic < ActiveRecord::Base - before_destroy :destroy_author, 'puts "I'm an inline fragment"' - end - - Learn more in link:classes/ActiveRecord/Callbacks.html - -* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when - the holder is destroyed: - - class Album < ActiveRecord::Base - has_many :tracks, :dependent => true - end - - All the associated tracks are destroyed when the album is. - -* Added Base.create as a factory that'll create, save, and return a new object in one step. - -* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you - to pass the argument hashes directly from yaml. (Luke) - -* Fixed the install.rb to include simple.rb [Spotted by Kevin Bullock] - -* Modified block syntax to better follow our code standards outlined in - http://www.rubyonrails.org/CodingStandards - - -*0.8.1* - -* Added object-level transactions [Austin Ziegler] - -* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection, - which is parametized through a config hash with symbol keys instead of a regular parameter list. - This will allow for database connections to be opened in a more generic fashion. (Luke) - - NOTE: This requires all *_connections to be updated! Read more in: - http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081 - -* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes - (t.name is now name). [Spotted by Garrett Rooney] - -* Fixed SQLite adapter so dates are returned as Date objects, not Time objects [Spotted by Gavin Sinclair] - -* Fixed requirement of date class, so date conversions are succesful regardless of whether you - manually require date or not. - - -*0.8.0* - -* Added transactions - -* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7]) - as parameter and then return an array of objects instead of just an object - -* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a - collection, not an association - -* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type - aren't treated as current time [Spotted by Gavin Sinclair] - - -*0.7.6* - -* Fixed the install.rb to create the lib/active_record/support directory [Spotted by Gavin Sinclair] -* Fixed that has_association? would always return true [Daniel Von Fange] diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md new file mode 100644 index 0000000000..c4feabfb5f --- /dev/null +++ b/activerecord/CHANGELOG.md @@ -0,0 +1,6741 @@ +## Rails 4.0.0 (unreleased) ## + +* Connections *must* be closed at the end of a thread. If not, your + connection pool can fill and an exception will be raised. + +* Added the `ActiveRecord::Model` module which can be included in a + class as an alternative to inheriting from `ActiveRecord::Base`: + + class Post + include ActiveRecord::Model + end + + Please note: + + * Up until now it has been safe to assume that all AR models are + descendants of `ActiveRecord::Base`. This is no longer a safe + assumption, but it may transpire that there are areas of the + code which still make this assumption. So there may be + 'teething difficulties' with this feature. (But please do try it + and report bugs.) + + * Plugins & libraries etc that add methods to `ActiveRecord::Base` + will not be compatible with `ActiveRecord::Model`. Those libraries + should add to `ActiveRecord::Model` instead (which is included in + `Base`), or better still, avoid monkey-patching AR and instead + provide a module that users can include where they need it. + + * To minimise the risk of conflicts with other code, it is + advisable to include `ActiveRecord::Model` early in your class + definition. + + *Jon Leighton* + +* PostgreSQL hstore records can be created. + +* PostgreSQL hstore types are automatically deserialized from the database. + +## Rails 3.2.0 (unreleased) ## + +* Added ability to run migrations only for given scope, which allows + to run migrations only from one engine (for example to revert changes + from engine that you want to remove). + + Example: + rake db:migrate SCOPE=blog + + *Piotr Sarnacki* + +* Migrations copied from engines are now scoped with engine's name, + for example 01_create_posts.blog.rb. *Piotr Sarnacki* + +* Implements `AR::Base.silence_auto_explain`. This method allows the user to + selectively disable automatic EXPLAINs within a block. *fxn* + +* Implements automatic EXPLAIN logging for slow queries. + + A new configuration parameter `config.active_record.auto_explain_threshold_in_seconds` + determines what's to be considered a slow query. Setting that to `nil` disables + this feature. Defaults are 0.5 in development mode, and `nil` in test and production + modes. + + As of this writing there's support for SQLite, MySQL (mysql2 adapter), and + PostgreSQL. + + *fxn* + +* Implemented ActiveRecord::Relation#pluck method + + Method returns Array of column value from table under ActiveRecord model + + Client.pluck(:id) + + *Bogdan Gusiev* + +* Automatic closure of connections in threads is deprecated. For example + the following code is deprecated: + + Thread.new { Post.find(1) }.join + + It should be changed to close the database connection at the end of + the thread: + + Thread.new { + Post.find(1) + Post.connection.close + }.join + + Only people who spawn threads in their application code need to worry + about this change. + +* Deprecated: + + * `set_table_name` + * `set_inheritance_column` + * `set_sequence_name` + * `set_primary_key` + * `set_locking_column` + + Use an assignment method instead. For example, instead of `set_table_name`, use `self.table_name=`: + + class Project < ActiveRecord::Base + self.table_name = "project" + end + + Or define your own `self.table_name` method: + + class Post < ActiveRecord::Base + def self.table_name + "special_" + super + end + end + Post.table_name # => "special_posts" + + *Jon Leighton* + +* Generated association methods are created within a separate module to allow overriding and + composition using `super`. For a class named `MyModel`, the module is named + `MyModel::GeneratedFeatureMethods`. It is included into the model class immediately after + the `generated_attributes_methods` module defined in ActiveModel, so association methods + override attribute methods of the same name. *Josh Susser* + +* Implemented ActiveRecord::Relation#explain. *fxn* + +* Add ActiveRecord::Relation#uniq for generating unique queries. + + Before: + + Client.select('DISTINCT name') + + After: + + Client.select(:name).uniq + + This also allows you to revert the unqueness in a relation: + + Client.select(:name).uniq.uniq(false) + + *Jon Leighton* + +* Support index sort order in sqlite, mysql and postgres adapters. *Vlad Jebelev* + +* Allow the :class_name option for associations to take a symbol (:Client) in addition to + a string ('Client'). + + This is to avoid confusing newbies, and to be consistent with the fact that other options + like :foreign_key already allow a symbol or a string. + + *Jon Leighton* + +* In development mode the db:drop task also drops the test database. For symmetry with + the db:create task. *Dmitriy Kiriyenko* + +* Added ActiveRecord::Base.store for declaring simple single-column key/value stores *DHH* + + class User < ActiveRecord::Base + store :settings, accessors: [ :color, :homepage ] + end + + u = User.new(color: 'black', homepage: '37signals.com') + u.color # Accessor stored attribute + u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor + + +* MySQL: case-insensitive uniqueness validation avoids calling LOWER when + the column already uses a case-insensitive collation. Fixes #561. + + *Joseph Palermo* + +* Transactional fixtures enlist all active database connections. You can test + models on different connections without disabling transactional fixtures. + + *Jeremy Kemper* + +* Add first_or_create, first_or_create!, first_or_initialize methods to Active Record. This is a + better approach over the old find_or_create_by dynamic methods because it's clearer which + arguments are used to find the record and which are used to create it: + + User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson") + + *Andrés Mejía* + +* Fix nested attributes bug where _destroy parameter is taken into account + during :reject_if => :all_blank (fixes #2937) + + *Aaron Christy* + +## Rails 3.1.3 (unreleased) ## + +* Perf fix: If we're deleting all records in an association, don't add a IN(..) clause + to the query. *GH 3672* + + *Jon Leighton* + +* Fix bug with referencing other mysql databases in set_table_name. *GH 3690* + +* Fix performance bug with mysql databases on a server with lots of other databses. *GH 3678* + + *Christos Zisopoulos and Kenny J* + +## Rails 3.1.2 (unreleased) ## + +* Fix bug with PostgreSQLAdapter#indexes. When the search path has multiple schemas, spaces + were not being stripped from the schema names after the first. + + *Sean Kirby* + +* Preserve SELECT columns on the COUNT for finder_sql when possible. *GH 3503* + + *Justin Mazzi* + +* Reset prepared statement cache when schema changes impact statement results. *GH 3335* + + *Aaron Patterson* + +* Postgres: Do not attempt to deallocate a statement if the connection is no longer active. + + *Ian Leitch* + +* Prevent QueryCache leaking database connections. *GH 3243* + + *Mark J. Titorenko* + +* Fix bug where building the conditions of a nested through association could potentially + modify the conditions of the through and/or source association. If you have experienced + bugs with conditions appearing in the wrong queries when using nested through associations, + this probably solves your problems. *GH #3271* + + *Jon Leighton* + +* If a record is removed from a has_many :through, all of the join records relating to that + record should also be removed from the through association's target. + + *Jon Leighton* + +* Fix adding multiple instances of the same record to a has_many :through. *GH #3425* + + *Jon Leighton* + +* Fix creating records in a through association with a polymorphic source type. *GH #3247* + + *Jon Leighton* + +* MySQL: use the information_schema than the describe command when we look for a primary key. *GH #3440* + + *Kenny J* + +## Rails 3.1.1 (October 7, 2011) ## + +* Add deprecation for the preload_associations method. Fixes #3022. + + *Jon Leighton* + +* Don't require a DB connection when loading a model that uses set_primary_key. GH #2807. + + *Jon Leighton* + +* Fix using select() with a habtm association, e.g. Person.friends.select(:name). GH #3030 and + \#2923. + + *Hendy Tanata* + +* Fix belongs_to polymorphic with custom primary key on target. GH #3104. + + *Jon Leighton* + +* CollectionProxy#replace should change the DB records rather than just mutating the array. + Fixes #3020. + + *Jon Leighton* + +* LRU cache in mysql and sqlite are now per-process caches. + + * lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache keys are per process id. + * lib/active_record/connection_adapters/sqlite_adapter.rb: ditto + *Aaron Patterson* + +* Support bulk change_table in mysql2 adapter, as well as the mysql one. *Jon Leighton* + +* If multiple parameters are sent representing a date, and some are blank, the + resulting object is nil. In previous releases those values defaulted to 1. This only affects existing but blank parameters, missing ones still raise an error. [Akira Matsuda] +* ActiveRecord::Base.establish_connection now takes a string that contains + a URI that specifies the connection configuration. For example: + ActiveRecord::Base.establish_connection 'postgres://localhost/foo' + +* Active Record's dynamic finder will now raise the error if you passing in less number of arguments than what you call in method signature. + + So if you were doing this and expecting the second argument to be nil: + + User.find_by_username_and_group("sikachu") + + You'll now get `ArgumentError: wrong number of arguments (1 for 2).` You'll then have to do this: + + User.find_by_username_and_group("sikachu", nil) + + *Prem Sichanugrist* + + +## Rails 3.1.0 (August 30, 2011) ## + +* Add a proxy_association method to association proxies, which can be called by association + extensions to access information about the association. This replaces proxy_owner etc with + proxy_association.owner. + + *Jon Leighton* + +* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature. + + Before: def build_association(*options) + After: def build_association(*options, &block) + + Users who are redefining this method to extend functionality should ensure that the block is + passed through to ActiveRecord::Base#new. + + This change is necessary to fix https://github.com/rails/rails/issues/1842. + + *Jon Leighton* + +* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model: + + class User < ActiveRecord::Base + self.pluralize_table_names = false + end + + Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. *Guillermo Iguaran* + +* Add block setting of attributes to singular associations: + + class User < ActiveRecord::Base + has_one :account + end + + user.build_account{ |a| a.credit_limit => 100.0 } + + The block is called after the instance has been initialized. *Andrew White* + +* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. *Prem Sichanugrist* + +* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0 + +* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you + to specify which role to consider when assigning attributes. This is built on top of ActiveModel's + new mass assignment capabilities: + + class Post < ActiveRecord::Base + attr_accessible :title + attr_accessible :title, :published_at, :as => :admin + end + + Post.new(params[:post], :as => :admin) + + assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated. + + Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly. + + *Josh Kalderimis* + +* default_scope can take a block, lambda, or any other object which responds to `call` for lazy + evaluation: + + default_scope { ... } + default_scope lambda { ... } + default_scope method(:foo) + + This feature was originally implemented by Tim Morgan, but was then removed in favour of + defining a 'default_scope' class method, but has now been added back in by Jon Leighton. + The relevant lighthouse ticket is #1812. + +* Default scopes are now evaluated at the latest possible moment, to avoid problems where + scopes would be created which would implicitly contain the default scope, which would then + be impossible to get rid of via Model.unscoped. + + Note that this means that if you are inspecting the internal structure of an + ActiveRecord::Relation, it will *not* contain the default scope, though the resulting + query will do. You can get a relation containing the default scope by calling + ActiveRecord#with_default_scope, though this is not part of the public API. + + *Jon Leighton* + +* If you wish to merge default scopes in special ways, it is recommended to define your default + scope as a class method and use the standard techniques for sharing code (inheritance, mixins, + etc.): + + class Post < ActiveRecord::Base + def self.default_scope + where(:published => true).where(:hidden => false) + end + end + + *Jon Leighton* + +* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher. + +* ConnectionManagement middleware is changed to clean up the connection pool + after the rack body has been flushed. + +* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks. + It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of + the updated_at column. It should not be called on new records. + Example: + + User.first.update_column(:name, "sebastian") # => true + + *Sebastian Martinez* + +* Associations with a :through option can now use *any* association as the + through or source association, including other associations which have a + :through option and has_and_belongs_to_many associations + + *Jon Leighton* + +* The configuration for the current database connection is now accessible via + ActiveRecord::Base.connection_config. *fxn* + +* limits and offsets are removed from COUNT queries unless both are supplied. + For example: + + People.limit(1).count # => 'SELECT COUNT(*) FROM people' + People.offset(1).count # => 'SELECT COUNT(*) FROM people' + People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1' + + *lighthouse #6262* + +* ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class + (and subclasses) which are responsible for operating on associations, and then a separate, + thin wrapper called CollectionProxy, which proxies collection associations. + + This prevents namespace pollution, separates concerns, and will allow further refactorings. + + Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return + the associated record or nil. This means that you should not use undocumented methods such + as bob.mother.create - use bob.create_mother instead. + + *Jon Leighton* + +* Make has_many :through associations work correctly when you build a record and then save it. This + requires you to set the :inverse_of option on the source reflection on the join model, like so: + + class Post < ActiveRecord::Base + has_many :taggings + has_many :tags, :through => :taggings + end + + class Tagging < ActiveRecord::Base + belongs_to :post + belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set! + end + + class Tag < ActiveRecord::Base + has_many :taggings + has_many :posts, :through => :taggings + end + + post = Post.first + tag = post.tags.build :name => "ruby" + tag.save # will save a Taggable linking to the post + + *Jon Leighton* + +* Support the :dependent option on has_many :through associations. For historical and practical + reasons, :delete_all is the default deletion strategy employed by association.delete(*records), + despite the fact that the default strategy is :nullify for regular has_many. Also, this only + works at all if the source reflection is a belongs_to. For other situations, you should directly + modify the through association. + + *Jon Leighton* + +* Changed the behaviour of association.destroy for has_and_belongs_to_many and has_many :through. + From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', + not (necessarily) 'get rid of the associated records'. + + Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It + would not delete any records in the join table. Now, it deletes the records in the join table. + + Previously, has_many_through.destroy(*records) would destroy the records themselves, and the + records in the join table. [Note: This has not always been the case; previous version of Rails + only deleted the records themselves.] Now, it destroys only the records in the join table. + + Note that this change is backwards-incompatible to an extent, but there is unfortunately no + way to 'deprecate' it before changing it. The change is being made in order to have + consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. + + If you wish to destroy the records themselves, you can do records.association.each(&:destroy) + + *Jon Leighton* + +* Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. *Pratik Naik* + + Example: + + change_table(:users, :bulk => true) do |t| + t.string :company_name + t.change :birthdate, :datetime + end + + This will now result in: + + ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL + +* Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been + documented as deprecated behaviour since April 2006. Please use has_many :through instead. + *Jon Leighton* + +* Added a create_association! method for has_one and belongs_to associations. *Jon Leighton* + +* Migration files generated from model and constructive migration generators + (for example, add_name_to_users) use the reversible migration's `change` + method instead of the ordinary `up` and `down` methods. *Prem Sichanugrist* + +* Removed support for interpolating string SQL conditions on associations. Instead, you should + use a proc, like so: + + Before: + + has_many :things, :conditions => 'foo = #{bar}' + + After: + + has_many :things, :conditions => proc { "foo = #{bar}" } + + Inside the proc, 'self' is the object which is the owner of the association, unless you are + eager loading the association, in which case 'self' is the class which the association is within. + + You can have any "normal" conditions inside the proc, so the following will work too: + + has_many :things, :conditions => proc { ["foo = ?", bar] } + + Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call + 'record' to get the record being inserted or deleted. This is now passed as an argument to + the proc. + +* Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example: + + # Schema: User(name:string, password_digest:string, password_salt:string) + class User < ActiveRecord::Base + has_secure_password + end + + user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch") + user.save # => false, password required + user.password = "mUc3m00RsqyRe" + user.save # => false, confirmation doesn't match + user.password_confirmation = "mUc3m00RsqyRe" + user.save # => true + user.authenticate("notright") # => false + user.authenticate("mUc3m00RsqyRe") # => user + User.find_by_name("david").try(:authenticate, "notright") # => nil + User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user + + +* When a model is generated add_index is added by default for belongs_to or references columns + + rails g model post user:belongs_to will generate the following: + + class CreatePosts < ActiveRecord::Migration + def up + create_table :posts do |t| + t.belongs_to :user + t.timestamps + end + + add_index :posts, :user_id + end + + def down + drop_table :posts + end + end + + *Santiago Pastorino* + +* Setting the id of a belongs_to object will update the reference to the + object. [#2989 state:resolved] +* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed + to closer match normal Ruby dup and clone semantics. +* Calling ActiveRecord::Base#clone will result in a shallow copy of the record, + including copying the frozen state. No callbacks will be called. +* Calling ActiveRecord::Base#dup will duplicate the record, including calling + after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable. +* Migrations can be defined as reversible, meaning that the migration system + will figure out how to reverse your migration. To use reversible migrations, just define the "change" method. For example: + class MyMigration < ActiveRecord::Migration + def change + create_table(:horses) do + t.column :content, :text + t.column :remind_at, :datetime + end + end + end + + Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define 'up' and 'down' in your migration. If you define something in `change` that cannot be reversed, an IrreversibleMigration exception will be raised when going down. +* Migrations should use instance methods rather than class methods: + class FooMigration < ActiveRecord::Migration + def up + ... + end + end + + *Aaron Patterson* + +* has_one maintains the association with separate after_create/after_update instead + of a single after_save. *fxn* + +* The following code: + + Model.limit(10).scoping { Model.count } + + now generates the following SQL: + + SELECT COUNT(*) FROM models LIMIT 10 + + This may not return what you want. Instead, you may with to do something + like this: + + Model.limit(10).scoping { Model.all.size } + + *Aaron Patterson* + + +## Rails 3.0.7 (April 18, 2011) ## + +* Destroying records via nested attributes works independent of reject_if LH #6006 *Durran Jordan* + +* Delegate any? and many? to Model.scoped for consistency *Andrew White* + +* Quote the ORDER BY clause in batched finds - fixes #6620 *Andrew White* + +* Change exists? so records are not instantiated - fixes #6127. This prevents after_find + and after_initialize callbacks being triggered when checking for record existence. + *Andrew White* + +* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we + cache type-casted values when the column returned from the db contains non-standard chars. + *Jon Leighton* + +* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8 + related to read_attribute method *Stian Grytøyr* + + +## Rails 3.0.6 (April 5, 2011) ## + +* Un-deprecate reorder method *Sebastian Martinez* + +* Extensions are applied when calling +except+ or +only+ on relations. + Thanks to Iain Hecker. + +* Schemas set in set_table_name are respected by the mysql adapter. LH #5322 + +* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded. + LH #5829 + +* Reapply extensions when using except and only. Thanks Iain Hecker. + +* Binary data is escaped when being inserted to SQLite3 Databases. Thanks + Naruse! + + +## Rails 3.0.5 (February 26, 2011) ## + +* Model.where(:column => 1).where(:column => 2) will always produce an AND + query. + *Aaron Patterson* + +* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'. + + Instead, you should use a proc, like so: + + Before: + + has_many :things, :conditions => 'foo = #{bar}' + + After: + + has_many :things, :conditions => proc { "foo = #{bar}" } + + Inside the proc, 'self' is the object which is the owner of the association, unless you are + eager loading the association, in which case 'self' is the class which the association is within. + + You can have any "normal" conditions inside the proc, so the following will work too: + + has_many :things, :conditions => proc { ["foo = ?", bar] } + + Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call + 'record' to get the record being inserted or deleted. This is now passed as an argument to + the proc. + + *Jon Leighton* + + +## Rails 3.0.4 (February 8, 2011) ## + +* Added deprecation warning for has_and_belongs_to_many associations where the join table has + additional attributes other than the keys. Access to these attributes is removed in 3.1. + Please use has_many :through instead. *Jon Leighton* + + +## Rails 3.0.3 (November 16, 2010) ## + +* Support find by class like this: Post.where(:name => Post) + + +## Rails 3.0.2 (November 15, 2010) ## + +* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) *Aaron Patterson* + +* reorder is deprecated in favor of except(:order).order(...) *Santiago Pastorino* + +* except is now AR public API + + Model.order('name').except(:order).order('salary') + + generates: + + SELECT * FROM models ORDER BY salary + + *Santiago Pastorino* + +* The following code: + + Model.limit(10).scoping { Model.count } + + now generates the following SQL: + + SELECT COUNT(*) FROM models LIMIT 10 + + This may not return what you want. Instead, you may with to do something + like this: + + Model.limit(10).scoping { Model.all.size } + + *Aaron Patterson* + + +## Rails 3.0.1 (October 15, 2010) ## + +* Introduce a fix for CVE-2010-3993 + + +## Rails 3.0.0 (August 29, 2010) ## + +* Changed update_attribute to not run callbacks and update the record directly in the database *Neeraj Singh* + +* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope *José Valim* + +* New rake task, db:migrate:status, displays status of migrations #4947 *Kevin Skoglund* + +* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten *Santiago Pastorino* + +* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 *Aaron Patterson* + +* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 *Andrew Bloomgarden, Andrew White* + +* Add index length support for MySQL. #1852 *Emili Parreno, Pratik Naik* + + Example: + + add_index(:accounts, :name, :name => 'by_name', :length => 10) + => CREATE INDEX by_name ON accounts(name(10)) + + add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15}) + => CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) + +* find_or_create_by_attr(value, ...) works when attr is protected. #4457 *Santiago Pastorino, Marc-André Lafortune* + +* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 *Brian Durand* + +* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). *José Valim* + +* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 *Curtis Hawthorne* + +* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. *Jeremy Kemper* + +* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 *Mislav Marohnić* + +* Add Relation extensions. *Pratik Naik* + + users = User.where(:admin => true).extending(User::AdminPowers) + + latest_users = User.order('created_at DESC') do + def posts_count + Post.count(:user_id => to_a.map(&:id)) + end + end + +* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 *Andrew White* + +* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development *DHH* + +* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 *Jack Christensen* + +* Allow relations to be used as scope. + + class Item + scope :red, where(:colour => 'red') + end + + Item.red.limit(10) # Ten red items + +* Rename named_scope to scope. *Pratik Naik* + +* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default *DHH* + +* Add Relation#except. *Pratik Naik* + + one_red_item = Item.where(:colour => 'red').limit(1) + all_items = one_red_item.except(:where, :limit) + +* Add Relation#delete_all. *Pratik Naik* + + Item.where(:colour => 'red').delete_all + +* Add Model.having and Relation#having. *Pratik Naik* + + Developer.group("salary").having("sum(salary) > 10000").select("salary") + +* Add Relation#count. *Pratik Naik* + + legends = People.where("age > 100") + legends.count + legends.count(:age, :distinct => true) + legends.select('id').count + +* Add Model.readonly and association_collection#readonly finder method. *Pratik Naik* + + Post.readonly.to_a # Load all posts in readonly mode + @user.items.readonly(false).to_a # Load all the user items in writable mode + +* Add .lock finder method *Pratik Naik* + + User.lock.where(:name => 'lifo').to_a + + old_items = Item.where("age > 100") + old_items.lock.each {|i| .. } + +* Add Model.from and association_collection#from finder methods *Pratik Naik* + + user = User.scoped + user.select('*').from('users, items') + +* Add relation.destroy_all *Pratik Naik* + + old_items = Item.where("age > 100") + old_items.destroy_all + +* Add relation.exists? *Pratik Naik* + + red_items = Item.where(:colours => 'red') + red_items.exists? + red_items.exists?(1) + +* Add find(ids) to relations. *Pratik Naik* + + old_users = User.order("age DESC") + old_users.find(1) + old_users.find(1, 2, 3) + +* Add new finder methods to association collection. *Pratik Naik* + + class User < ActiveRecord::Base + has_many :items + end + + user = User.first + user.items.where(:items => {:colour => 'red'}) + user.items.select('items.id') + +* Add relation.reload to force reloading the records. *Pratik Naik* + + topics = Topic.scoped + topics.to_a # force load + topics.first # returns a cached record + topics.reload + topics.first # Fetches a new record from the database + +* Rename Model.conditions and relation.conditions to .where. *Pratik Naik* + + Before : + User.conditions(:name => 'lifo') + User.select('id').conditions(["age > ?", 21]) + + Now : + User.where(:name => 'lifo') + User.select('id').where(["age > ?", 21]) + +* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. *Pratik Naik* + + Examples : + + posts = Post.select('id).order('name') # Returns a lazy relation + posts.each {|p| puts p.id } # Fires "select id from posts order by name" + +* Model.scoped now returns a relation if invoked without any arguments. *Pratik Naik* + + Example : + + posts = Post.scoped + posts.size # Fires "select count(*) from posts" and returns the count + posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects + +* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 *Murray Steele* + + # post.comments sets each comment's post without needing to :include + class Post < ActiveRecord::Base + has_many :comments, :inverse_of => :post + end + +* MySQL: add_ and change_column support positioning. #3286 *Ben Marini* + +* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 *Mike Breen, Gabe da Silveira* + +* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git *Pratik Naik* + +* PostgreSQL: XML datatype support. #1874 *Leonardo Borges* + +* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 *Geoff Buesing* + +* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 *Paul Hinze, Jeremy Kemper* + +* Added :primary_key option to belongs_to associations. #765 *Szymon Nowak, Philip Hallstrom, Noel Rocha* + # employees.company_name references companies.name + Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name' + +* Implement #many? for NamedScope and AssociationCollection using #size. #1500 *Chris Kampmeier* + +* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed *DHH* + +* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time *DHH* + + +## 2.3.2 Final (March 15, 2009) ## + +* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing *DHH/Jamis Buck* + +* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 *Scott Taylor* + +* Add Support for updating deeply nested models from a single form. #1202 *Eloy Duran* + + class Book < ActiveRecord::Base + has_one :author + has_many :pages + + accepts_nested_attributes_for :author, :pages + end + +* Make after_save callbacks fire only if the record was successfully saved. #1735 *Michael Lovitt* + + Previously the callbacks would fire if a before_save cancelled saving. + +* Support nested transactions using database savepoints. #383 *Jonathan Viney, Hongli Lai* + +* Added dynamic scopes ala dynamic finders #1648 *Yaroslav Markin* + +* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 *Yaroslav Markin* + +* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 *Akira Matsuda* + +* Add :having as a key to find and the relevant associations. *Emilio Tagua* + +* Added default_scope to Base #1381 [Paweł Kondzior]. Example: + + class Person < ActiveRecord::Base + default_scope :order => 'last_name, first_name' + end + + class Company < ActiveRecord::Base + has_many :people + end + + Person.all # => Person.find(:all, :order => 'last_name, first_name') + Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 }) + + +## 2.2.1 RC2 (November 14th, 2008) ## + +* Ensure indices don't flip order in schema.rb #1266 *Jordi Bunster* + +* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 *Andreas Korth* + + +## 2.2.0 RC1 (October 24th, 2008) ## + +* Skip collection ids reader optimization if using :finder_sql *Jeremy Kemper* + +* Add Model#delete instance method, similar to Model.delete class method. #1086 *Hongli Lai (Phusion)* + +* MySQL: cope with quirky default values for not-null text columns. #1043 *Frederick Cheung* + +* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] *Geoff Buesing* + +* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] *Emilio Tagua* + +* Added find_last_by dynamic finder #762 *Emilio Tagua* + +* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 *Hongli Lai (Phusion)* + +* Changed benchmarks to be reported in milliseconds *David Heinemeier Hansson* + +* Connection pooling. #936 *Nick Sieger* + +* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 *Andrew White* + +* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 *Xavier Noria* + +* Transactional migrations for databases which support them. #834 *divoxx, Adam Wiggins, Tarmo Tänav* + +* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. *Andrew Stone, Nik Wakelin* + +* change_column_default preserves the not-null constraint. #617 *Tarmo Tänav* + +* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) *#334* + +* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example : + + \# Ensure essay contains at least 100 words. + validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) } + +* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example: + + User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } } + Item.first :conditions => { :items => { :color => 'red' } } + +* Always treat integer :limit as byte length. #420 *Tarmo Tänav* + +* Partial updates don't update lock_version if nothing changed. #426 *Daniel Morrison* + +* Fix column collision with named_scope and :joins. #46 *Duncan Beevers, Mark Catley* + +* db:migrate:down and :up update schema_migrations. #369 *Michael Raidel, RaceCondition* + +* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. *Tarmo Tänav* + +* MySQL: rename_column preserves column defaults. #466 *Diego Algorta* + +* Add :from option to calculations. #397 *Ben Munat* + +* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. *Jan De Poorter* + +* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. *Jeremy Kemper* + +* Added SQL escaping for :limit and :offset in MySQL *Jonathan Wiess* + + +## 2.1.0 (May 31st, 2008) ## + +* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. *Rick Olson* + +* Add first/last methods to associations/named_scope. Resolved #226. *Ryan Bates* + +* Added SQL escaping for :limit and :offset #288 *Aaron Bedra, Steven Bristol, Jonathan Wiess* + +* Added first/last methods to associations/named_scope. Resolved #226. *Ryan Bates* + +* Ensure hm:t preloading honours reflection options. Resolves #137. *Frederick Cheung* + +* Added protection against duplicate migration names (Aslak Hellesøy) *#112* + +* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true *Geoff Buesing* + +* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. *Scott Fleckenstein, Geoff Buesing* + +* Added change_table for migrations (Jeff Dean) [#71]. Example: + + change_table :videos do |t| + t.timestamps # adds created_at, updated_at + t.belongs_to :goat # adds goat_id integer + t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit + t.remove :name, :email # removes the name and email columns + end + +* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) *#85* + +* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) *#39* + +* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) *#67* + +* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] *#26* + +* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL *David Heinemeier Hansson* + +* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. *Rick Olson* + +* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 *Jordi Bunster* + +* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 *Kamal Fariz Mahyuddin* + +* Ensure that respond_to? considers dynamic finder methods. Closes #11538. *James Mead* + +* Ensure that save on parent object fails for invalid has_one association. Closes #10518. *Pratik Naik* + +* Remove duplicate code from associations. *Pratik Naik* + +* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 *Ruy Asan* + +* Ensure HABTM#create and HABTM#build do not load entire association. *Pratik Naik* + +* Improve documentation. *Xavier Noria, Jack Danger Canty, leethal* + +* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} *Rick Olson* + + Post.find(1).to_json # => {"title": ...} + config.active_record.include_root_in_json = true + Post.find(1).to_json # => {"post": {"title": ...}} + +* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). *stopdropandrew* + +* PostgreSQL: create_ and drop_database support. #9042 *ez, pedz, Nick Sieger* + +* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. *Nik Wakelin, cavalle* + +* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. *Jeremy Kemper* + +* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled *Geoff Buesing* + +* Fixed that validates_size_of :within works in associations #11295, #10019 *cavalle* + +* Track changes to unsaved attributes. *Jeremy Kemper* + +* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 *John Barnette* + +* Fixed that has_many :through would ignore the hash conditions #11447 *Emilio Tagua* + +* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 *cavalle* + +* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 *cavalle* + +* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 *Jack Danger Canty* + +* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert* + +* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 *Emilio Tagua* + +* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 *nkallen, Chris O'Sullivan* + +* Merge the has_finder gem, renamed as 'named_scope'. #11404 *nkallen* + + class Article < ActiveRecord::Base + named_scope :published, :conditions => {:published => true} + named_scope :popular, :conditions => ... + end + + Article.published.paginate(:page => 1) + Article.published.popular.count + Article.popular.find(:first) + Article.popular.find(:all, :conditions => {...}) + + See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries + +* Add has_one :through support. #4756 *Chris O'Sullivan* + +* Migrations: create_table supports primary_key_prefix_type. #10314 *student, Chris O'Sullivan* + +* Added logging for dependency load errors with fixtures #11056 *stuthulhu* + +* Time zone aware attributes use Time#in_time_zone *Geoff Buesing* + +* Fixed that scoped joins would not always be respected #6821 *Theory/Jack Danger Canty* + +* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 *cavalle* + +* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 *jramirez* + +* Added ActiveRecord::Base.find(:last) #11338 *Emilio Tagua* + +* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition *Geoff Buesing* + +* Add :readonly option to HasManyThrough associations. #11156 *Emilio Tagua* + +* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 *dasil003* + +* Perf fix: Avoid the use of named block arguments. Closes #11109 *adymo* + +* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 *jdavis* + +* Ensure association preloading doesn't break when an association returns nil. ##11145 *GMFlash* + +* Make dynamic finders respect the :include on HasManyThrough associations. #10998. *cpytel* + +* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability *Geoff Buesing* + +* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback *Geoff Buesing* + +* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 *adymo* + +* Optimise the BigDecimal conversion code. #11110 *adymo* + +* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 *Emilio Tagua* + +* Multiparameter attributes for time columns fail over to DateTime when out of range of Time *Geoff Buesing* + +* Base#instantiate_time_object uses Time.zone.local() *Geoff Buesing* + +* Add timezone-aware attribute readers and writers. #10982 *Geoff Buesing* + +* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 *Rick Olson* + +* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 *Xavier Noria* + +* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 *mdeiters* + +* belongs_to supports :dependent => :destroy and :delete. #10592 *Jonathan Viney* + +* Introduce preload query strategy for eager :includes. #9640 *Frederick Cheung, Aliaksey Kandratsenka, codafoo* + +* Support aggregations in finder conditions. #10572 *Ryan Kinderman* + +* Organize and clean up the Active Record test suite. #10742 *John Barnette* + +* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 *john.andrews* + +* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 *railsjitsu* + +* Fixtures: removed support for the ancient pre-YAML file format. #10736 *John Barnette* + +* More thoroughly quote table names. #10698 *dimdenis, lotswholetime, Jeremy Kemper* + +* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 *Brendan Ribera* + +* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries *David Heinemeier Hansson* + +* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. *JEG2* + +* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 *Sam* + +* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 *jamesh, Frederick Cheung, protocool* + +* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 *stopdropandrew, canadaduane* + +* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 *Jonathan Viney* + +* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 *Brandon Keepers* + +* Ruby 1.9 compatibility. #10655 *Jeremy Kemper, Dirkjan Bussink* + + +## 2.0.2 (December 16th, 2007) ## + +* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 *Rick Olson* + +* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 *brynary* + +* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 *Josh Susser* + +* Ensure that the :uniq option for has_many :through associations retains the order. #10463 *remvee* + +* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 *Michael Klishin* + +* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 *Michael Klishin* + + +## 2.0.1 (December 7th, 2007) ## + +* Removed query cache rescue as it could cause code to be run twice (closes #10408) *David Heinemeier Hansson* + + +## 2.0.0 (December 6th, 2007) ## + +* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ *Geoff Buesing* + +* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) *David Heinemeier Hansson* + +* Fixed that the truncation of strings longer than 50 chars should use inspect + so newlines etc are escaped #10385 [Norbert Crombach] +* Fixed that habtm associations should be able to set :select as part of their definition and have that honored *David Heinemeier Hansson* + +* Document how the :include option can be used in Calculations::calculate. Closes #7446 *adamwiggins, ultimoamore* + +* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 *johnjosephbachir* + +* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 *adamwiggins, mikong* + +* More complete documentation for find_by_sql. Closes #7912 *fearoffish* + +* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example: + + render :partial => @client.becomes(Company) # renders companies/company instead of clients/client + +* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 *Cheah Chu Yeow* + +* Fix documentation typo introduced in [8250]. Closes #10339 *Henrik N* + +* Foxy fixtures: support single-table inheritance. #10234 *tom* + +* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 *lotswholetime* + +* Make the record_timestamps class-inheritable so it can be set per model. #10004 *tmacedo* + +* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 *ambethia* + +* DateTimes use Ruby's default calendar reform setting. #10201 *Geoff Buesing* + +* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 *Patrick Joyce, Rick Olson, Jack Danger Canty* + +* Add 'foxy' support for fixtures of polymorphic associations. #10183 *John Barnette, David Lowenfels* + +* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 *devrieda, Mike Naberezny* + +* attr_readonly behaves well with optimistic locking. #10188 *Nick Bugajski* + +* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 *Jonathan del Strother* + +* Change plings to the more conventional quotes in the documentation. Closes #10104 *Jack Danger Canty* + +* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 *Jack Danger Canty* + +* Ensure that column names are quoted. Closes #10134 *wesley.moxam* + +* Smattering of grammatical fixes to documentation. Closes #10083 *Bob Silva* + +* Enhance explanation with more examples for attr_accessible macro. Closes #8095 *fearoffish, Marcel Molina Jr.* + +* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 *Pratik Naik* + +* Explain semantics of having several different AR instances in a transaction block. Closes #9036 *jacobat, Marcel Molina Jr.* + +* Update Schema documentation to use updated sexy migration notation. Closes #10086 *Sam Granieri* + +* Make fixtures work with the new test subclasses. *Tarmo Tänav, Michael Koziarski* + +* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 *RubyRedRick* + # Find users with an avatar + User.find(:all, :joins => :avatar) + + # Find posts with a high-rated comment. + Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3') + +* Associations: speedup duplicate record check. #10011 *Pratik Naik* + +* Make sure that << works on has_many associations on unsaved records. Closes #9989 *Josh Susser* + +* Allow association redefinition in subclasses. #9346 *wildchild* + +* Fix has_many :through delete with custom foreign keys. #6466 *naffis* + +* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README) + - stable, autogenerated IDs + - specify associations (belongs_to, has_one, has_many) by label, not ID + - specify HABTM associations as inline lists + - autofill timestamp columns + - support YAML defaults + - fixture label interpolation + Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 *John Barnette* + +* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 *boone, rmm5t* + +* Update add_index documentation to use new options api. Closes #9787 *Kamal Fariz Mahyuddin* + +* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 *krishna* + +* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 *sur* + +* Limited eager loading no longer ignores scoped :order. Closes #9561 *Jack Danger Canty, Josh Peek* + +* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 *brandon, Chris Cruft* + +* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 *Chris Cruft* + +* Ensure that mysql quotes table names with database names correctly. Closes #9911 *crayz* + + "foo.bar" => "`foo`.`bar`" + +* Complete the assimilation of Sexy Migrations from ErrFree *Chris Wanstrath, PJ Hyett* + http://errtheblog.com/post/2381 + +* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 *Jack Danger Canty* + +* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 *Bryan Helmkamp* + +* Refactor association create and build so before & after callbacks behave consistently. #8854 *Pratik Naik, mortent* + +* Quote table names. Defaults to column quoting. #4593 *Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper* + +* Alias association #build to #new so it behaves predictably. #8787 *Pratik Naik* + +* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 *saimonmoore, Rick Olson* + +* Observers can observe model names as symbols properly now. Closes #9869 *queso* + +* find_and_(initialize|create)_by methods can now properly initialize protected attributes *Tobias Lütke* + +* belongs_to infers the foreign key from the association name instead of from the class name. *Jeremy Kemper* + +* PostgreSQL: support multiline default values. #7533 *Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav* + +* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 *Jonathan Viney, Tarmo Tänav* + +* validates_uniqueness_of behaves well with abstract superclasses and + single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat] +* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 *Henrik N* + +* Speedup database date/time parsing. *Jeremy Kemper, Tarmo Tänav* + +* Fix calling .clear on a has_many :dependent=>:delete_all association. *Tarmo Tänav* + +* Allow change_column to set NOT NULL in the PostgreSQL adapter *Tarmo Tänav* + +* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. *Rick Olson* + +* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. *Rick Olson* + +* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. *Jeremy Kemper, Derrick Spell* + + +## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.14.2 - 1.15.3 ## + +* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 *Dan Manges* + + class Comment < ActiveRecord::Base + # Automatically sets Article#comments_count as readonly. + belongs_to :article, :counter_cache => :comments_count + end + + class Article < ActiveRecord::Base + attr_readonly :approved_comments_count + end + +* Make size for has_many :through use counter cache if it exists. Closes #9734 *Xavier Shay* + +* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. *Jeremy Kemper* + +* Extract Oracle, SQLServer, and Sybase adapters into gems. *Jeremy Kemper* + +* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 *Frederick Cheung* + +* Correctly quote id list for limited eager loading. #7482 *tmacedo* + +* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 *valeksenko* + +* Fixed rename_column for SQLite when using symbols for the column names #8616 *drodriguez* + +* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 *Robby Russell, Tarmo Tänav* + +* Added ActiveRecord::Base#to_json/from_json *David Heinemeier Hansson, Cheah Chu Yeow* + +* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example: + + xml = "<person><name>David</name></person>" + Person.new.from_xml(xml).name # => "David" + +* Define dynamic finders as real methods after first usage. *bscofield* + +* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. *Jeremy Kemper* + +* Associations macros accept extension blocks alongside modules. #9346 *Josh Peek* + +* Speed up and simplify query caching. *Jeremy Kemper* + +* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 *Michael Schuerig* + +* Eager loading respects explicit :joins. #9496 *dasil003* + +* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 *Jeremy Kemper* + +* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. *Jeremy Kemper* + +* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 *TimoMihaljov/brandon* + +* Fix association writer with :dependent => :nullify. #7314 *Jonathan Viney* + +* OpenBase: update for new lib and latest Rails. Support migrations. #8748 *dcsesq* + +* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 *Pratik Naik* + +* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 *Josh Peek* + +* Moved acts_as_list into a plugin of the same name on the official Rails svn. *Josh Peek* + +* Explicitly require active_record/query_cache before using it. *Jeremy Kemper* + +* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. *Rick Olson, marclove* + +* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. *Jeremy Kemper* + +* Fixed that eager loading queries and with_scope should respect the :group option *David Heinemeier Hansson* + +* Improve performance and functionality of the postgresql adapter. Closes #8049 *roderickvd* + + For more information see: http://dev.rubyonrails.org/ticket/8049 + +* Don't clobber includes passed to has_many.count *Jack Danger Canty* + +* Make sure has_many uses :include when counting *Jack Danger Canty* + +* Change the implementation of ActiveRecord's attribute reader and writer methods *Michael Koziarski* + - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns. - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns. - Move method definition to the class, instead of the instance - Always generate the readers, writers and predicate methods. +* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. *Rick Olson* + + \# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik] +* Added :unless clause to validations #8003 [monki]. Example: + + def using_open_id? + !identity_url.blank? + end + + validates_presence_of :identity_url, :if => using_open_id? + validates_presence_of :username, :unless => using_open_id? + validates_presence_of :password, :unless => using_open_id? + +* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 *Pratik Naik* + +* Fix and properly document/test count(column_name) usage. Closes #8999 *Pratik Naik* + +* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 *Pratik Naik* + +* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 *Josh Susser* + + OLD + belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id + + NEW + belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id + +* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 *Pratik Naik* + +* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 *Pratik Naik* + +* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 *dasil003* + +* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, *Manfred Stienstra, jwilger* + +* Define collection singular ids method for has_many :through associations. #8763 *Pratik Naik* + +* Array attribute conditions work with proxied association collections. #8318 *Kamal Fariz Mahyuddin, theamazingrando* + +* Fix polymorphic has_one associations declared in an abstract class. #8638 *Pratik Naik, Dax Huiberts* + +* Fixed validates_associated should not stop on the first error. #4276 *mrj, Manfred Stienstra, Josh Peek* + +* Rollback if commit raises an exception. #8642 *kik, Jeremy Kemper* + +* Update tests' use of fixtures for the new collections api. #8726 *Kamal Fariz Mahyuddin* + +* Save associated records only if the association is already loaded. #8713 *Blaine* + +* MySQL: fix show_variable. #8448 *matt, Jeremy Kemper* + +* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 *Michael Schuerig* + +* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 *technomancy, Josh Peek* + +* Calculations support non-numeric foreign keys. #8154 *Kamal Fariz Mahyuddin* + +* with_scope is protected. #8524 *Josh Peek* + +* Quickref for association methods. #7723 *marclove, Mindsweeper* + +* Calculations: return nil average instead of 0 when there are no rows to average. #8298 *davidw* + +* acts_as_nested_set: direct_children is sorted correctly. #4761 *Josh Peek, rails@33lc0.net* + +* Raise an exception if both attr_protected and attr_accessible are declared. #8507 *stellsmi* + +* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 *marclove, lorenjohnson* + +* Allow nil serialized attributes with a set class constraint. #7293 *sandofsky* + +* Oracle: support binary fixtures. #7987 *Michael Schoen* + +* Fixtures: pull fixture insertion into the database adapters. #7987 *Michael Schoen* + +* Announce migration versions as they're performed. *Jeremy Kemper* + +* find gracefully copes with blank :conditions. #7599 *Dan Manges, johnnyb* + +* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 *Bob Silva, Dan Kubb, Josh Peek* + +* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 *matt* + +* Find with a list of ids supports limit/offset. #8437 *hrudududu* + +* Optimistic locking: revert the lock version when an update fails. #7840 *plang* + +* Migrations: add_column supports custom column types. #7742 *jsgarvin, Theory* + +* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. *Jeremy Kemper* + +* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 *Jack Danger Canty, Josh Peek, Rick Olson* + +* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 *mmangino@elevatedrails.com* + +* Fix column type detection while loading fixtures. Closes #7987 *roderickvd* + +* Document deep eager includes. #6267 *Josh Susser, Dan Manges* + +* Document warning that associations names shouldn't be reserved words. #4378 *murphy@cYcnus.de, Josh Susser* + +* Sanitize Base#inspect. #8392, #8623 *Nik Wakelin, jnoon* + +* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. *Michael Koziarski* + +* Oracle: extract column length for CHAR also. #7866 *ymendel* + +* Document :allow_nil option for validates_acceptance_of since it defaults to true. *tzaharia* + +* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. *Jack Danger Canty* + +* Add documentation caveat about when to use count_by_sql. *fearoffish* + +* Enhance documentation for increment_counter and decrement_counter. *fearoffish* + +* Provide brief introduction to what optimistic locking is. *fearoffish* + +* Add documentation for :encoding option to mysql adapter. *marclove* + +* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example: + + create_table "products" do |t| + t.column "shop_id", :integer + t.column "creator_id", :integer + t.column "name", :string, :default => "Untitled" + t.column "value", :string, :default => "Untitled" + t.column "created_at", :datetime + t.column "updated_at", :datetime + end + + ...can now be written as: + + create_table :products do |t| + t.integer :shop_id, :creator_id + t.string :name, :value, :default => "Untitled" + t.timestamps + end + +* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. *Michael Koziarski, jstrachan* + +* Improve performance of calling .create on has_many :through associations. *evan* + +* Improved cloning performance by relying less on exception raising #8159 *Blaine* + +* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> *David Heinemeier Hansson* + +* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls *David Heinemeier Hansson* + +* Small additions and fixes for ActiveRecord documentation. Closes #7342 *Jeremy McAnally* + +* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. *court3nay* + +* SQLite: binary escaping works with $KCODE='u'. #7862 *tsuka* + +* Base#to_xml supports serialized attributes. #7502 *jonathan* + +* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. *Jeremy Kemper* + +* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 *Michael Koziarski, Jeremy Kemper* + +* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. *Jeremy Kemper* + +* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 *Josh Susser* + +* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. *Michael Koziarski* + +* Allow a polymorphic :source for has_many :through associations. Closes #7143 *protocool* + +* Consistent public/protected/private visibility for chained methods. #7813 *Dan Manges* + +* Oracle: fix quoted primary keys and datetime overflow. #7798 *Michael Schoen* + +* Consistently quote primary key column names. #7763 *toolmantim* + +* Fixtures: fix YAML ordered map support. #2665 *Manuel Holtgrewe, nfbuckley* + +* DateTimes assume the default timezone. #7764 *Geoff Buesing* + +* Sybase: hide timestamp columns since they're inherently read-only. #7716 *Mike Joyce* + +* Oracle: overflow Time to DateTime. #7718 *Michael Schoen* + +* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 *flowdelic, toolmantim* + +* Fix has_many :through << with custom foreign keys. #6466, #7153 *naffis, Rich Collins* + +* Test DateTime native type in migrations, including an edge case with dates + during calendar reform. #7649, #7724 [fedot, Geoff Buesing] +* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 *Jakob Skjerning, Tom Ward* + +* SQLServer: recognize real column type as Ruby float. #7057 *sethladd, Tom Ward* + +* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 *Manfred Stienstra* + +* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example: + + transaction do |transaction| + david.withdrawal(100) + mary.deposit(100) + transaction.rollback! # rolls back the transaction that was otherwise going to be successful + end + +* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method *Jamis Buck* + +* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however *Tobias Lütke* + Task.cache { Task.find(1); Task.find(1) } # => 1 query + +* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck* + +* Oracle: fix lob and text default handling. #7344 *gfriedrich, Michael Schoen* + +* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning* + +* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 *Dan Kubb* + +* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 *sandofsky, Assaf* + +* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc* + +* Use Date#to_s(:db) for quoted dates. #7411 *Michael Schoen* + +* Don't create instance writer methods for class attributes. Closes #7401 *Rick Olson* + +* Docs: validations examples. #7343 *zackchandler* + +* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 *sandofsky* + +* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden* + +* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 *Josh Susser* + +* Fix minor doc typos. Closes #7157 *Josh Susser* + +* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 *Josh Susser* + +* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org* + +* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 *BertG, nick+rails@ag.arizona.edu* + +* Make sure sqlite3 driver closes open connections on disconnect *Rob Rasmussen* + +* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally* + +* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper* + +* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com* + +* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen* + +* MySQL: retain SSL settings on reconnect. #6976 *randyv2* + +* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. *Cody Fauser* + +* SQLServer: handle [quoted] table names. #6635 *rrich* + +* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser* + +* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen* + +* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges* + Student.find(:all, :conditions => { :grade => 9..12 }) + +* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler* + +* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell* + +* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot* + +* Bring the sybase adapter up to scratch for 1.2 release. *jsheets* + +* Rollback new_record? and id when an exception is raised in a save callback. #6910 *Ben Curren, outerim* + +* Pushing a record on an association collection doesn't unnecessarily load all the associated records. *Obie Fernandez, Jeremy Kemper* + +* Oracle: fix connection reset failure. #6846 *leonlleslie* + +* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper* + +* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool* + +* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 *Alexander Dymo, Tobias Lütke* + +* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper* + +* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute *Cody Fauser* + +* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form *David Heinemeier Hansson* + +* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 *Zach Dennis* + +* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov* + +* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 *Jonathan Viney* + +* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz* + +* Run validations in the order they were declared. #6657 *obrie* + +* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper* + +* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 *martin* + +* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen* + +* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen* + +* Don't inspect unloaded associations. #2905 *lmarlow* + +* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 *careo, lukfugl* + +* Cache inheritance_column. #6592 *Stefan Kaes* + +* Firebird: decimal/numeric support. #6408 *macrnic* + +* make add_order a tad faster. #6567 *Stefan Kaes* + +* Find with :include respects scoped :order. #5850 + +* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper* + find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } + +* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si* + +* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. *Jeremy Kemper* + +* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 *Bob Silva* + +* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes* + +* Deprecation: object transactions warning. *Jeremy Kemper* + +* has_one :dependent => :nullify ignores nil associates. #4848, #6528 *bellis@deepthought.org, janovetz, Jeremy Kemper* + +* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen* + +* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie* + +* Document other options available to migration's add_column. #6419 *grg* + +* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper* + +* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney* + +* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson* + +* Restore eager condition interpolation, document it's differences *Rick Olson* + +* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper* + +* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers* + +* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson* + +* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com* + +* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com* + +* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan* + +* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva* + +* The has_many create method works with polymorphic associations. #6361 *Dan Peterson* + +* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes* + +* save! shouldn't validate twice. #6324 *maiha, Bob Silva* + +* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig* + +* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson* + +* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva* + +* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper* + +* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski* + +* Add a :namespace option to AR::Base#to_xml *Michael Koziarski* + +* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper* + +* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson* + +* Improve yaml fixtures error reporting. #6205 *Bruce Williams* + +* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski* + +* Add deprecation warning for inferred foreign key. #6029 *Josh Susser* + +* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com* + +* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser* + +* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 *Bob Silva* + +* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward* + +* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher* + +* Deprecation: update docs. #5998 *Jakob Skjerning, Kevin Clark* + +* Add some XmlSerialization tests for ActiveRecord *Rick Olson* + +* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com* + +* Tighten rescue clauses. #5985 *james@grayproductions.net* + +* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck* + +* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney* + +* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney* + +* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi* + +* SQLServer: fix eager association test. #5901 *Tom Ward* + +* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark* + +* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com* + +* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com* + +* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward* + +* to_xml: correct naming of included associations. #5831 *Josh Starcher* + +* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser* + +* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper* + + # Create a tagging to associate the post and tag. + post.tags << Tag.find_by_name('old') + post.tags.create! :name => 'general' + + # Would have been: + post.taggings.create!(:tag => Tag.find_by_name('finally') + transaction do + post.taggings.create!(:tag => Tag.create!(:name => 'general')) + end + +* Cache nil results for :included has_one associations also. #5787 *Michael Schoen* + +* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke* + +* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper* + Example: Invoice::Lineitem is given table name invoice_lineitems + +* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper* + # people_active_last_name_index, people_active_deactivated_at_index + add_index :people, [:active, :last_name] + add_index :people, [:active, :deactivated_at] + remove_index :people, [:active, :last_name] + remove_index :people, [:active, :deactivated_at] + + WARNING: backward-incompatibility. Multicolumn indexes created before this + revision were named using the first column name only. Now they're uniquely + named using all indexed columns. + + To remove an old multicolumn index, remove_index :table_name, :first_column + +* Fix for deep includes on the same association. *richcollins@gmail.com* + +* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark* + +* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson* + +* Document find's :from option. Closes #5762. *andrew@redlinesoftware.com* + +* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com* + +* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar* + +* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen* + +* Add documentation for how to disable timestamps on a per model basis. Closes #5684. *matt@mattmargolis.net Marcel Molina Jr.* + +* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney* + +* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson* + +* Formally deprecate the deprecated finders. *Michael Koziarski* + +* Formally deprecate rich associations. *Michael Koziarski* + +* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com* + +* Fix announcement of very long migration names. #5722 *blake@near-time.com* + +* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com* + +* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com* + +* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: + + assert (Topic.exists?(:author_name => "David")) + assert (Topic.exists?(:author_name => "Mary", :approved => true)) + assert (Topic.exists?(["parent_id = ?", 1])) + +* Schema dumper quotes date :default values. *Dave Thomas* + +* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson* + +* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper* + +* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck* + +* Allow #count through a has_many association to accept :include. *Dan Peterson* + +* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw* + +* PostgreSQL: return array fields as strings. #4664 *Robby Russell* + +* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward* + +* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers* + +* Oracle: BigDecimal support. #5667 *Michael Schoen* + +* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk* + +* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>* + +* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com* + +* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>* + +* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net* + +* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com* + +* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net* + +* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen* + +* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen* + +* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org* + +* Minor tweak to improve performance of ActiveRecord::Base#to_param. + +* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au* + +* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper* + +* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com* + +* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com* + +* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. + +* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson* + +* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda* + # Obtain an exclusive lock on person 1 so we can safely increment visits. + Person.transaction do + # select * from people where id=1 for update + person = Person.find(1, :lock => true) + person.visits += 1 + person.save! + end + +* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper* + +* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper* + +* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar* + +* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) + +* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson* + +* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: + + Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) + + ...is the same as: + Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) + + This makes it easier to pass in the options from a form or otherwise outside. + + +* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com* + +* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net* + +* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com* + +* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com* + +* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp* + +* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net* + +* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>* + +* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp* + +* Records and arrays of records are bound as quoted ids. *Jeremy Kemper* + Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) + Foo.find(:first, :conditions => ['bar_id = ?', bar]) + +* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson* + +* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson* + +* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser* + +* Provide Association Extensions access to the instance that the association is being accessed from. + Closes #4433 *Josh Susser* + +* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell* + +* Add a quick note about :select and eagerly included associations. *Rick Olson* + +* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com* + +* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson* + +* Added :allow_nil option for aggregations #5091 *Ian White* + +* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen* + +* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper* + +* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com* + +* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk* + +* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org* + +* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com* + +* Allow :uniq => true with has_many :through associations. *Jeremy Kemper* + +* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.* + +* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com* + +* Replace superfluous name_to_class_name variant with camelize. *Marcel Molina Jr.* + +* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.* + +* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.* + +* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>* + +* Update FrontBase adapter to check binding version. Closes #4920. *mlaster@metavillage.com* + +* New Frontbase connections don't start in auto-commit mode. Closes #4922. *mlaster@metavillage.com* + +* When grouping, use the appropriate option key. *Marcel Molina Jr.* + +* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. *Marcel Molina Jr.* + +* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com* + +* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>* + +* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić* + +* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu* + +* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com* + +* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net* + +* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>* + +* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com* + +* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net* + +* Fix bug where calculations with long alias names return null. *Rick Olson* + +* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson* + + @post.tags << @tag # BAD + @post.taggings.create(:tag => @tag) # GOOD + +* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson* + +* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com* + +* Add ActiveRecord::Errors#to_xml *Jamis Buck* + +* Properly quote index names in migrations (closes #4764) *John Long* + +* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson* + +* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson* + +* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson* + +* DRY up association collection reader method generation. *Marcel Molina Jr.* + +* DRY up and tweak style of the validation error object. *Marcel Molina Jr.* + +* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson* + + class Account < ActiveRecord::Base + validates_uniqueness_of :email, :case_sensitive => false + end + +* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser* + + class Account < ActiveRecord::Base + has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] + end + + *1.15.3* (March 12th, 2007) + + * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool] + + * Consistently quote primary key column names. #7763 [toolmantim] + + * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley] + + * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins] + + +## 1.15.2 (February 5th, 2007) ## + +* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges* + Student.find(:all, :conditions => { :grade => 9..12 }) + +* Don't create instance writer methods for class attributes. *Rick Olson* + +* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck* + +* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning* + +* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si* + +* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc* + +* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden* + +* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org* + + +## 1.15.1 (January 17th, 2007) ## + +* Fix nodoc breaking of adapters + + +## 1.15.0 (January 16th, 2007) ## + +* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally* + +* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper* + +* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com* + +* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen* + +* MySQL: retain SSL settings on reconnect. #6976 *randyv2* + +* SQLServer: handle [quoted] table names. #6635 *rrich* + +* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser* + +* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen* + +* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler* + +* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell* + +* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot* + +* Bring the sybase adapter up to scratch for 1.2 release. *jsheets* + +* Oracle: fix connection reset failure. #6846 *leonlleslie* + +* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper* + +* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool* + +* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper* + +* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper* + find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil } + +* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov* + +* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper* + +* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz* + +* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen* + +* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen* + +* Firebird: decimal/numeric support. #6408 *macrnic* + +* Find with :include respects scoped :order. #5850 + +* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes* + +* Deprecation: object transactions warning. *Jeremy Kemper* + +* has_one :dependent => :nullify ignores nil associates. #6528 *janovetz, Jeremy Kemper* + +* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen* + +* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie* + +* Document other options available to migration's add_column. #6419 *grg* + +* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper* + +* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney* + +* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson* + +* Restore eager condition interpolation, document it's differences *Rick Olson* + +* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper* + +* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers* + +* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson* + +* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com* + +* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com* + +* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan* + +* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva* + +* The has_many create method works with polymorphic associations. #6361 *Dan Peterson* + +* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes* + +* save! shouldn't validate twice. #6324 *maiha, Bob Silva* + +* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig* + +* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson* + +* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva* + +* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper* + +* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski* + +* Add a :namespace option to AR::Base#to_xml *Michael Koziarski* + +* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper* + +* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson* + +* Improve yaml fixtures error reporting. #6205 *Bruce Williams* + +* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski* + +* Add deprecation warning for inferred foreign key. #6029 *Josh Susser* + +* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com* + +* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser* + +* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward* + +* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher* + +* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com* + +* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck* + +* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney* + +* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney* + +* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi* + +* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark* + +* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com* + +* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com* + +* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward* + +* to_xml: correct naming of included associations. #5831 *Josh Starcher* + +* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser* + +* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper* + + # Create a tagging to associate the post and tag. + post.tags << Tag.find_by_name('old') + post.tags.create! :name => 'general' + + # Would have been: + post.taggings.create!(:tag => Tag.find_by_name('finally') + transaction do + post.taggings.create!(:tag => Tag.create!(:name => 'general')) + end + +* Cache nil results for :included has_one associations also. #5787 *Michael Schoen* + +* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke* + +* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper* + Example: Invoice::Lineitem is given table name invoice_lineitems + +* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper* + # people_active_last_name_index, people_active_deactivated_at_index + add_index :people, [:active, :last_name] + add_index :people, [:active, :deactivated_at] + remove_index :people, [:active, :last_name] + remove_index :people, [:active, :deactivated_at] + + WARNING: backward-incompatibility. Multicolumn indexes created before this + revision were named using the first column name only. Now they're uniquely + named using all indexed columns. + + To remove an old multicolumn index, remove_index :table_name, :first_column + +* Fix for deep includes on the same association. *richcollins@gmail.com* + +* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark* + +* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson* + +* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com* + +* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar* + +* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen* + +* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney* + +* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson* + +* Formally deprecate the deprecated finders. *Michael Koziarski* + +* Formally deprecate rich associations. *Michael Koziarski* + +* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com* + +* Fix announcement of very long migration names. #5722 *blake@near-time.com* + +* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com* + +* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com* + +* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples: + + assert (Topic.exists?(:author_name => "David")) + assert (Topic.exists?(:author_name => "Mary", :approved => true)) + assert (Topic.exists?(["parent_id = ?", 1])) + +* Schema dumper quotes date :default values. *Dave Thomas* + +* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson* + +* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper* + +* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck* + +* Allow #count through a has_many association to accept :include. *Dan Peterson* + +* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw* + +* PostgreSQL: return array fields as strings. #4664 *Robby Russell* + +* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward* + +* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers* + +* Oracle: BigDecimal support. #5667 *Michael Schoen* + +* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk* + +* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>* + +* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com* + +* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net* + +* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com* + +* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net* + +* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen* + +* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen* + +* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org* + +* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au* + +* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper* + +* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com* + +* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com* + +* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum. + +* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson* + +* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda* + # Obtain an exclusive lock on person 1 so we can safely increment visits. + Person.transaction do + # select * from people where id=1 for update + person = Person.find(1, :lock => true) + person.visits += 1 + person.save! + end + +* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper* + +* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper* + +* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar* + +* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de) + +* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson* + +* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example: + + Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2) + + ...is the same as: + Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2) + + This makes it easier to pass in the options from a form or otherwise outside. + + +* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com* + +* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net* + +* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com* + +* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com* + +* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp* + +* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net* + +* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>* + +* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp* + +* Records and arrays of records are bound as quoted ids. *Jeremy Kemper* + Foo.find(:all, :conditions => ['bar_id IN (?)', bars]) + Foo.find(:first, :conditions => ['bar_id = ?', bar]) + +* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson* + +* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson* + +* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser* + +* Provide Association Extensions access to the instance that the association is being accessed from. + Closes #4433 *Josh Susser* + +* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell* + +* Add a quick note about :select and eagerly included associations. *Rick Olson* + +* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com* + +* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson* + +* Added :allow_nil option for aggregations #5091 *Ian White* + +* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen* + +* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper* + +* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com* + +* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk* + +* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org* + +* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com* + +* Allow :uniq => true with has_many :through associations. *Jeremy Kemper* + +* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.* + +* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com* + +* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>* + +* When grouping, use the appropriate option key. *Marcel Molina Jr.* + +* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com* + +* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>* + +* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić* + +* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu* + +* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com* + +* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net* + +* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>* + +* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com* + +* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net* + +* Fix bug where calculations with long alias names return null. *Rick Olson* + +* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson* + + @post.tags << @tag # BAD + @post.taggings.create(:tag => @tag) # GOOD + +* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson* + +* Add ActiveRecord::Errors#to_xml *Jamis Buck* + +* Properly quote index names in migrations (closes #4764) *John Long* + +* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson* + +* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson* + +* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson* + +* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson* + + class Account < ActiveRecord::Base + validates_uniqueness_of :email, :case_sensitive => false + end + +* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser* + + class Account < ActiveRecord::Base + has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension] + end + + +## 1.14.4 (August 8th, 2006) ## + +* Add warning about the proper way to validate the presence of a foreign key. #4147 *Francois Beausoleil <francois.beausoleil@gmail.com>* + +* Fix syntax error in documentation. #4679 *Mislav Marohnić* + +* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com* + + +## 1.14.3 (June 27th, 2006) ## + +* Fix announcement of very long migration names. #5722 *blake@near-time.com* + +* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>* + +* Properly quote index names in migrations (closes #4764) *John Long* + +* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson* + +* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson* + + +## 1.14.2 (April 9th, 2006) ## + +* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen* + + +## 1.14.1 (April 6th, 2006) ## + +* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar* + +* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind* + +* Enable Limit/Offset in Calculations (closes #4558) *lmarlow* + +* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson* + +* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr* + +* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis* + +* Support eager includes when going through a polymorphic has_many association. *Rick Olson* + +* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson* + + class Post < ActiveRecord::Base + has_one :tagging, :as => :taggable + end + + Post.find :all, :include => :tagging + +* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson* + +* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson* + + class PhotoCollection < ActiveRecord::Base + has_many :photos, :as => :photographic + belongs_to :firm + end + + class Firm < ActiveRecord::Base + has_many :photo_collections + has_many :photos, :through => :photo_collections + end + +* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com* + +* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber* + +* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan* + +* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson* + +* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson* + +* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson* + +* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.* + +* Fixed broken OCIAdapter #4457 *Michael Schoen* + + +## 1.14.0 (March 27th, 2006) ## + +* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar* + +* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson* + +* Add support for :include to with_scope *andrew@redlinesoftware.com* + +* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen* + +* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com* + +* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson* + +* Fixed issue that kept :select options from being scoped *Rick Olson* + +* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson* + +* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson* + +* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson* + + class Connection < ActiveRecord::Base + belongs_to :user + belongs_to :channel + end + + class Channel < ActiveRecord::Base + has_many :connections + has_many :contacts, :through => :connections, :class_name => 'User' # OLD + has_many :contacts, :through => :connections, :source => :user # NEW + end + +* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de* + +* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson* + + In this example, :include => false disables the default eager association from loading. :select changes the standard + select clause. :joins specifies a join that is added to the end of the has_many :through query. + + class Post < ActiveRecord::Base + has_many :tags, :through => :taggings, :include => :tagging do + def add_joins_and_select + find :all, :select => 'tags.*, authors.id as author_id', :include => false, + :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' + end + end + end + +* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson* + +* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney* + +* Quit ignoring default :include options in has_many :through calls *Mark James* + +* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney* + +* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson* + +* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: + + class Firm < ActiveRecord::Base + has_many :clients + has_many :invoices, :through => :clients + end + + class Client < ActiveRecord::Base + belongs_to :firm + has_many :invoices + end + + class Invoice < ActiveRecord::Base + belongs_to :client + end + +* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser* + +* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney* + +* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson* + +* SQL Server adapter gets some love #4298 *Ryan Tomayko* + +* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com* + +* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): + + Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') + +* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson* + +* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski* + +* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski* + +* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward* + +* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com* + +* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck* + +* Use association's :conditions when eager loading. [Jeremy Evans] #4144 + +* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans* + + This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. + + Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') + +* Oracle adapter gets some love #4230 *Michael Schoen* + + * Changes :text to CLOB rather than BLOB [Moses Hohman] + * Fixes an issue with nil numeric length/scales (several) + * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] + * Tweaks a unit test to get it all green again + * Adds support for #current_database + +* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson* + + class CachedModel < ActiveRecord::Base + self.abstract_class = true + end + + class Post < CachedModel + end + + CachedModel.abstract_class? + => true + + Post.abstract_class? + => false + + Post.base_class + => Post + + Post.table_name + => 'posts' + +* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson* + + class Foo < ActiveRecord::Base + has_many :attachments, :as => :attachable, :dependent => :delete_all + end + +* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay* + +* Upgrade to Transaction::Simple 1.3 *Jamis Buck* + +* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson* + +* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com* + +* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com* + +* Dynamically set allow_concurrency. #4044 *Stefan Kaes* + +* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: + + topic.to_xml + + ...returns: + + <?xml version="1.0" encoding="UTF-8"?> + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <id type="integer">1</id> + <approved type="boolean">false</approved> + <replies-count type="integer">0</replies-count> + <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> + <written-on type="datetime">2003-07-16 09:28:00</written-on> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + ...and you can configure with: + + topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) + + ...that'll return: + + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <approved type="boolean">false</approved> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + You can even do load first-level associations as part of the document: + + firm.to_xml :include => [ :account, :clients ] + + ...that'll return something like: + + <?xml version="1.0" encoding="UTF-8"?> + <firm> + <id type="integer">1</id> + <rating type="integer">1</rating> + <name>37signals</name> + <clients> + <client> + <rating type="integer">1</rating> + <name>Summit</name> + </client> + <client> + <rating type="integer">1</rating> + <name>Microsoft</name> + </client> + </clients> + <account> + <id type="integer">1</id> + <credit-limit type="integer">50</credit-limit> + </account> + </firm> + +* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck* + +* Documentation fixes for :dependent *robby@planetargon.com* + +* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney* + +* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org* + +* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson* + +* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>* + +* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson* + + * The first time a table is referenced in a join, no alias is used. + * After that, the parent class name and the reflection name are used. + + Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... + + * Any additional join references get a numerical suffix like '_2', '_3', etc. + +* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. + +* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: + + # cascaded in two levels + >> Author.find(:all, :include=>{:posts=>:comments}) + => authors + +- posts + +- comments + + # cascaded in two levels and normal association + >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in two levels with two has_many associations + >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in three levels + >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) + => companies + +- groups + +- members + +- favorites + +* Make counter cache work when replacing an association #3245 *eugenol@gmail.com* + +* Make migrations verbose *Jamis Buck* + +* Make counter_cache work with polymorphic belongs_to *Jamis Buck* + +* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp* + +* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: + + * Does not support DATE SQL column types; use DATETIME instead. + * Date columns on HABTM join tables are returned as String, not Time. + * Insertions are potentially broken for :polymorphic join tables + * BLOB column access not yet fully supported + +* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper* + +* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper* + +* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen* + +* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson* + +* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes* + +* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark* + +* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net* + +* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney* + +* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward* + +* Added support for nested scopes #3407 [anna@wota.jp]. Examples: + + Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 + + # inner rule is used. (all previous parameters are ignored) + Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') + end + + # parameters are merged + Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 + end + end + +* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com* + +* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh* + +* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind* + +* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: + + Person.average :age + Person.minimum :age + Person.maximum :age + Person.sum :salary, :group => :last_name + +* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath* + +* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper* + +* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net* + +* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de* + +* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes* + +* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva* + +* Allow :include to be used with has_many :through associations #3611 *Michael Schoen* + +* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac* + +* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward* + +* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson* + +* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org* + +* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark* + +* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke* + +* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson* + +* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar* + +* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt* + +* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda* + +* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>* + +* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen* + +* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson* + +* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.* + +* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar* + +* Make .count work for has_many associations with multi line finder sql *Michael Schoen* + +* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck* + +* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com* + +* Don't hardcode 'id' in acts as list. *ror@philippeapril.com* + +* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark* + +* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp* + +* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com* + +* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke* + +* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.* + +* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de* + +* Sanitize scoped conditions. *Marcel Molina Jr.* + +* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson* + +* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke* + +* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke* + +* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber* + +* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron* + +* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke* + +* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke* + +* made .find() work on :through relations. *Tobias Lütke* + +* Fix typo in association docs. #3296. *Blair Zajac* + +* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke* + +## 1.13.2 (December 13th, 2005) ## + +* Become part of Rails 1.0 + +* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper* + +* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: + + class Post + has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author + end + + post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors + post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors + post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors + +* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson* + +* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder* + +* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com* + +* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org* + +* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com* + +* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko* + +* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com* + +* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen* + +* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes* + +* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil* + +* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond* + +* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson* + +* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen* + +* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper* + +* Added preliminary support for polymorphic associations *David Heinemeier Hansson* + +* Added preliminary support for join models *David Heinemeier Hansson* + +* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.* + +* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>* + +* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>* + +* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper* + +* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen* + +* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com* + +* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper* + +* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen* + +* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda* + +* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper* + +* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda* + +* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.* + +* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes* + +* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes* + +* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>* + +* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans* + +* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.* + +* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>* + +* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com* + +* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>* + +* Correct documentation for Base.delete_all. #1568 *Newhydra* + +* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>* + +* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>* + +* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper* + +* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>* + +* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper* + +* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper* + +* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper* + +* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko* + +* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>* + +* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de* + +* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>* + +* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com* + +* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar* + +* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney* + +* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper* + +* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.* + +* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com* + +* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper* + +* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper* + +* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>* + + +## 1.13.0 (November 7th, 2005) ## + +* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko* + +* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: + + has_many :posts, :include => [ :author, :comments ] + +* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: + + Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do + # Find where name = ? and active=true + Comment.find :all, :conditions => ['name = ?', name] + # Create comment associated with :post_id + Comment.create :body => "Hello world" + end + +* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko* + +* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: + + Comment.constrain(:creation => { :post_id => 5 }) do + # Associated with :post_id + Comment.create :body => "Hello world" + end + + This is rarely used directly, but allows for find_or_create on associations. So you can do: + + # If the tag doesn't exist, a new one is created that's associated with the person + person.tags.find_or_create_by_name("Summer") + +* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: + + # No 'Summer' tag exists + Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") + + # Now the 'Summer' tag does exist + Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") + +* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: + + class Account < ActiveRecord::Base + has_many :people do + def find_or_create_by_name(name) + first_name, *last_name = name.split + last_name = last_name.join " " + + find_or_create_by_first_name_and_last_name(first_name, last_name) + end + end + end + + person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") + person.first_name # => "David" + person.last_name # => "Heinemeier Hansson" + + Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). + +* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko* + +* Quote column names in generated SQL. #2728 *Ryan Tomayko* + +* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper* + +* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper* + +* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>* + +* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson* + +* Added migration support for Oracle #2647 *Michael Schoen* + +* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>* + +* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko* + +* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward* + +* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward* + +* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com* + +* Constraints are cloned so they can't be inadvertently modified while they're + in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] +* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com* + +* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen* + +* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt* + + +## 1.12.2 (October 26th, 2005) ## + +* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark* + +* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>* + +* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes* + +* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>* + +* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>* + +* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>* + + +## 1.12.1 (October 19th, 2005) ## + +* Always parenthesize :conditions options so they may be safely combined with STI and constraints. + +* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com* + +* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations + + +## 1.12.0 (October 16th, 2005) ## + +* Update/clean up documentation (rdoc) + +* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>* + +* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson* + +* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net* + +* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>* + +* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. + +* Avoid memleak in dev mode when using fcgi + +* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>* + +* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>* + +* Fix errors caused by assigning a has-one or belongs-to property to itself + +* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson* + +* Update DB2 adapter. #2206. *contact@maik-schmidt.de* + +* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com* + +* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. + +* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>* + +* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code* + +* Add test coverage for content_columns. #2432. *coffee2code* + +* Speed up for unthreaded environments. #2431. *Stefan Kaes* + +* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes* + +* Speed up the setting of table_name. #2428. *Stefan Kaes* + +* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes* + +* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>* + +* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes* + +* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>* + +* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick* + +* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes* + +* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes* + +* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar* + +* Added :force option to create_table that'll try to drop the table if it already exists before creating + +* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar* + +* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>* + +* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>* + +* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman* + +* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>* + +* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>* + +* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>* + +* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>* + +* Make update_attribute use the same writer method that update_attributes uses. + \#2237 [trevor@protocool.com] +* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.* + +* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org* + +* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com* + +* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) + +* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: + + ActiveRecord::Base.observers = :cacher, :garbage_collector + +* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com* + +* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck* + +* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck* + +* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck* + +* Fixed migrations for Windows when using more than 10 *David Naseby* + +* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber* + +* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke* + +* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar* + +* Fixed that Observers didn't observe sub-classes #627 *Florian Weber* + +* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.* + +* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae* + +* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber* + +* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil* + +* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com* + +* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg* + +* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward* + +* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code* + +* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net* + +* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ + +* Make sure the schema_info table is created before querying the current version #1903 + +* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning* + +* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine* + +* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz* + +* Make destroy return self #1913 *Sebastian Kanthak* + +* Fix typo in validations documentation #1938 *court3nay* + +* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org* + +* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky* + +* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com* + +* Fix create_table so that id column is implicitly added *Rick Olson* + +* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 + +* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 + +* Fixed the handling of camelCase columns names in Oracle #1798 + +* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 + +* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 + +* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke* + + class Comment < AR:B + def self.search(q) + find(:all, :conditions => ["body = ?", q]) + end + end + + class Post < AR:B + has_many :comments + end + + Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' + + NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as + by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on + details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself + noticed :) + +* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson* + +* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar* + +* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions + +* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt* + +* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes* + + +## 1.11.1 (11 July, 2005) ## + +* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson* + +* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com* + +* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson* + +* Correct reflected table name for singular associations. #1688 *court3nay* + +* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net* + +* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current + +* Added better error message for "packets out of order" #1630 *court3nay* + +* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 + + +## 1.11.0 (6 July, 2005) ## + +* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar* + +* Changed logging of SQL statements to use the DEBUG level instead of INFO + +* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. + +* Added callback hooks to association collections #1549 [Florian Weber]. Example: + + class Project + has_and_belongs_to_many :developers, :before_add => :evaluate_velocity + + def evaluate_velocity(developer) + ... + end + end + + ..raising an exception will cause the object not to be added (or removed, with before_remove). + + +* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry* + +* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato* + +* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber* + +* Speed up ActiveRecord#method_missing for the common case (read_attribute). + +* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes* + +* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath* + +* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at* + +* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig* + +* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry* + +* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry* + +* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net* + +* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl* + +* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: + + Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' + + ...should instead be: + + Developer.find( + :all, + :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', + :conditions => 'project_id=1' + ) + +* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.* + +* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon* + +* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 + +* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid* + +* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice + +* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper* + +* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. + Example: + + david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] + david.save + + If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new + project is saved when david.save is called. + + Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: + + david.project_ids = [1, 5, 7] + +* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com* + +* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke* + +* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org* + +* Corrected @@configurations typo #1410 *david@ruppconsulting.com* + +* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com* + +* Allow before/after update hooks to work on models using optimistic locking + +* Eager loading of dependent has_one associations won't delete the association #1212 + +* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. + +* Using transactional fixtures now causes the data to be loaded only once. + +* Added fixture accessor methods that can be used when instantiated fixtures are disabled. + + fixtures :web_sites + + def test_something + assert_equal "Ruby on Rails", web_sites(:rubyonrails).name + end + +* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar* + +* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar* + +* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 + +* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead + +* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: + + Conditional validations such as the following are made possible: + validates_numericality_of :income, :if => :employed? + + Conditional validations can also solve the salted login generator problem: + validates_confirmation_of :password, :if => :new_password? + + Using blocks: + validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } + +* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net* + +* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson* + +* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper* + +* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. + +* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. + +* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: + + # SELECT * FROM topics WHERE title IN ('First', 'Second') + Topic.find_all_by_title(["First", "Second"]) + +* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor* + +* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor* + +* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid* + +* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com* + +* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: + + development: + adapter: postgresql + database: rails_development + host: localhost + username: postgres + password: + encoding: UTF8 + min_messages: ERROR + +* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck* + +* Added validates_exclusion_of as a negative of validates_inclusion_of + +* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls + + +## 1.10.1 (20th April, 2005) ## + +* Fixed frivilous database queries being triggered with eager loading on empty associations and other things + +* Fixed order of loading in eager associations + +* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 + + +## 1.10.0 (19th April, 2005) ## + +* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: + + for post in Post.find(:all, :limit => 100) + puts "Post: " + post.title + puts "Written by: " + post.author.name + puts "Last comment on: " + post.comments.first.created_on + end + + This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: + + for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) + + ...and the number of database queries needed is now 1. + +* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: + + Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(:first, :order => "created_on DESC", :offset => 5) + Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) + Person.find(:all, :offset => 10, :limit => 10) + +* Added acts_as_nested_set #1000 [wschenk]. Introduction: + + This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with + the added feature that you can select the children and all of it's descendants with + a single query. A good use case for this is a threaded post system, where you want + to display every reply to a comment without multiple selects. + +* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas* + +* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com* + +* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com* + +* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com* + +* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher* + +* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle* + +* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com* + +* Added insert_at(position) to acts_as_list #1083 *DeLynnB* + +* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) + +* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com* + +* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org* + +* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 + +* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt* + +* Added quoting of column names for fixtures #997 *jcfischer@gmail.com* + +* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis* + +* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes* + +* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org* + +* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper* + +* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org* + +* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes* + +* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes* + +* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas* + +* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) + + +## 1.9.1 (27th March, 2005) ## + +* Fixed that Active Record objects with float attribute could not be cloned #808 + +* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar* + +* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count + +* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron* + +* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb* + + +## 1.9.0 (22th March, 2005) ## + +* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: + + Developer.find_all nil, 'id ASC', 5 # return the first five developers + Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward + + This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. + +* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson* + +* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins* + +* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org* + +* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel* + +* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid* + +* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com* + +* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net* + +* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak* + +* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak* + +* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm* + +* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself + +* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) + + +## 1.8.0 (7th March, 2005) ## + +* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) + +* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron* + +* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: + + * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the + +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ + objects that should be inspected to determine which attributes triggered the errors. + * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. + You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. + +* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k* + +* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper* + +* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: + + class Account < ActiveRecord::Base + has_one :credit_card, :dependent => true + end + class CreditCard < ActiveRecord::Base + belongs_to :account + end + + account.credit_card # => returns existing credit card, lets say id = 12 + account.credit_card = CreditCard.create("number" => "123") + account.save # => CC with id = 12 is destroyed + + +* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: + + Validates whether the value of the specified attribute is numeric by trying to convert it to + a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression + <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). + + class Person < ActiveRecord::Base + validates_numericality_of :value, :on => :create + end + + Configuration options: + * <tt>message</tt> - A custom error message (default is: "is not a number") + * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) + * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) + + +* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron* + +* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) + +* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com* + + +## 1.7.0 (24th February, 2005) ## + +* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck* + +* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: + + 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple + and safe way of passing table-specific sequence information to the adapter.) + 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to + resort to some hacks to get data converted to Date or Time in Ruby. + If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the + hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. + This is nasty - but if you use Duck Typing you'll probably not care very much. + In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is + valid - too many databases use DATE for both. + Timezones and sub-second precision on timestamps are not supported. + 3. Default values that are functions (such as "SYSDATE") are not supported. This is a + restriction of the way active record supports default values. + 4. Referential integrity constraints are not fully supported. Under at least + some circumstances, active record appears to delete parent and child records out of + sequence and out of transaction scope. (Or this may just be a problem of test setup.) + + The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ + +* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke* + +* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm* + +* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka* + +* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar* + +* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com* + +* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au* + +* Fixed that find_by_* would fail when column names had numbers #670 *demetrius* + +* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn* + + 1. Created a new columns method that is much cleaner. + 2. Corrected a problem with the select and select_all methods + that didn't account for the LIMIT clause being passed into raw SQL statements. + 3. Implemented the string_to_time method in order to create proper instances of the time class. + 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. + 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. + +* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow* + +* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: + + class Person < ActiveRecord::Base + validates_each :first_name, :last_name do |record, attr| + record.errors.add attr, 'starts with z.' if attr[0] == ?z + end + end + +* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper* + +* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: + + class Person < ActiveRecord::Base + validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } + end + +* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates* + +* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: + + class Project < ActiveRecord::Base + primary_key "sysid" + table_name "XYZ_PROJECT" + inheritance_column { original_inheritance_column + "_id" } + end + +* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu* + + +## 1.6.0 (January 25th, 2005) ## + +* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. + +* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 + +* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. + +* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example + + people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } + Person.update(people.keys, people.values) + +* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron* + +* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat* + +* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius* + +* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper* + +* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson* + +* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson* + +* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not + +* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription + +* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius* + +* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron* + + +## 1.5.1 (January 18th, 2005) ## + +* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates* + +* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle* + + +## 1.5.0 (January 17th, 2005) ## + +* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel* + +* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: + + class Book < ActiveRecord::Base + has_many :pages + belongs_to :library + + validates_associated :pages, :library + end + +* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: + + == Unsaved objects and associations + + You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be + aware of, mostly involving the saving of associated objects. + + === One-to-one associations + + * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in + order to update their primary keys - except if the parent object is unsaved (new_record? == true). + * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment + is cancelled. + * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). + * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does + not save the parent either. + + === Collections + + * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object + (the owner of the collection) is not yet stored in the database. + * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. + * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). + * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. + +* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates* + +* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates* + +* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates* + +* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates* + +* Fixed binary support for PostgreSQL #444 *alex@byzantine.no* + +* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the + collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If + it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, + it'll take one less SELECT query if you use length. + +* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de* + +* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson* + +* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey* + +* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz* + +* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper* + +* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower* + +* Added that Observers can use the observes class method instead of overwriting self.observed_class(). + + Before: + class ListSweeper < ActiveRecord::Base + def self.observed_class() [ List, Item ] + end + + After: + class ListSweeper < ActiveRecord::Base + observes List, Item + end + +* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is + +* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name + +* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. + + Before: topic.update_attribute(:approved, !approved?) + After : topic.toggle!(:approved) + +* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: + + page.views # => 1 + page.increment!(:views) # executes an UPDATE statement + page.views # => 2 + + page.increment(:views).increment!(:views) + page.views # => 4 + +* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. + + + + +## 1.14.2 (April 9th, 2005) ## + +* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen* + + +## 1.14.1 (April 6th, 2006) ## + +* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar* + +* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind* + +* Enable Limit/Offset in Calculations (closes #4558) *lmarlow* + +* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson* + +* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr* + +* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis* + +* Support eager includes when going through a polymorphic has_many association. *Rick Olson* + +* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson* + + class Post < ActiveRecord::Base + has_one :tagging, :as => :taggable + end + + Post.find :all, :include => :tagging + +* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson* + +* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson* + + class PhotoCollection < ActiveRecord::Base + has_many :photos, :as => :photographic + belongs_to :firm + end + + class Firm < ActiveRecord::Base + has_many :photo_collections + has_many :photos, :through => :photo_collections + end + +* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com* + +* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber* + +* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan* + +* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson* + +* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson* + +* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson* + +* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.* + +* Fixed broken OCIAdapter #4457 *Michael Schoen* + + +## 1.14.0 (March 27th, 2006) ## + +* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar* + +* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson* + +* Add support for :include to with_scope *andrew@redlinesoftware.com* + +* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen* + +* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com* + +* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson* + +* Fixed issue that kept :select options from being scoped *Rick Olson* + +* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson* + +* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson* + +* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson* + + class Connection < ActiveRecord::Base + belongs_to :user + belongs_to :channel + end + + class Channel < ActiveRecord::Base + has_many :connections + has_many :contacts, :through => :connections, :class_name => 'User' # OLD + has_many :contacts, :through => :connections, :source => :user # NEW + end + +* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de* + +* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson* + + In this example, :include => false disables the default eager association from loading. :select changes the standard + select clause. :joins specifies a join that is added to the end of the has_many :through query. + + class Post < ActiveRecord::Base + has_many :tags, :through => :taggings, :include => :tagging do + def add_joins_and_select + find :all, :select => 'tags.*, authors.id as author_id', :include => false, + :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' + end + end + end + +* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson* + +* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney* + +* Quit ignoring default :include options in has_many :through calls *Mark James* + +* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney* + +* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson* + +* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example: + + class Firm < ActiveRecord::Base + has_many :clients + has_many :invoices, :through => :clients + end + + class Client < ActiveRecord::Base + belongs_to :firm + has_many :invoices + end + + class Invoice < ActiveRecord::Base + belongs_to :client + end + +* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser* + +* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney* + +* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson* + +* SQL Server adapter gets some love #4298 *Ryan Tomayko* + +* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com* + +* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI): + + Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body') + +* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson* + +* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski* + +* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski* + +* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward* + +* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com* + +* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck* + +* Use association's :conditions when eager loading. [Jeremy Evans] #4144 + +* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans* + + This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous. + + Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL') + +* Oracle adapter gets some love #4230 *Michael Schoen* + + * Changes :text to CLOB rather than BLOB [Moses Hohman] + * Fixes an issue with nil numeric length/scales (several) + * Implements support for XMLTYPE columns [wilig / Kubo Takehiro] + * Tweaks a unit test to get it all green again + * Adds support for #current_database + +* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson* + + class CachedModel < ActiveRecord::Base + self.abstract_class = true + end + + class Post < CachedModel + end + + CachedModel.abstract_class? + => true + + Post.abstract_class? + => false + + Post.base_class + => Post + + Post.table_name + => 'posts' + +* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson* + + class Foo < ActiveRecord::Base + has_many :attachments, :as => :attachable, :dependent => :delete_all + end + +* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay* + +* Upgrade to Transaction::Simple 1.3 *Jamis Buck* + +* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson* + +* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com* + +* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com* + +* Dynamically set allow_concurrency. #4044 *Stefan Kaes* + +* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example: + + topic.to_xml + + ...returns: + + <?xml version="1.0" encoding="UTF-8"?> + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <id type="integer">1</id> + <approved type="boolean">false</approved> + <replies-count type="integer">0</replies-count> + <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time> + <written-on type="datetime">2003-07-16 09:28:00</written-on> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + ...and you can configure with: + + topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ]) + + ...that'll return: + + <topic> + <title>The First Topic</title> + <author-name>David</author-name> + <approved type="boolean">false</approved> + <content>Have a nice day</content> + <author-email-address>david@loudthinking.com</author-email-address> + <parent-id></parent-id> + <last-read type="date">2004-04-15</last-read> + </topic> + + You can even do load first-level associations as part of the document: + + firm.to_xml :include => [ :account, :clients ] + + ...that'll return something like: + + <?xml version="1.0" encoding="UTF-8"?> + <firm> + <id type="integer">1</id> + <rating type="integer">1</rating> + <name>37signals</name> + <clients> + <client> + <rating type="integer">1</rating> + <name>Summit</name> + </client> + <client> + <rating type="integer">1</rating> + <name>Microsoft</name> + </client> + </clients> + <account> + <id type="integer">1</id> + <credit-limit type="integer">50</credit-limit> + </account> + </firm> + +* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck* + +* Documentation fixes for :dependent *robby@planetargon.com* + +* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney* + +* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org* + +* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson* + +* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>* + +* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson* + + * The first time a table is referenced in a join, no alias is used. + * After that, the parent class name and the reflection name are used. + + Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ... + + * Any additional join references get a numerical suffix like '_2', '_3', etc. + +* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to. + +* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples: + + # cascaded in two levels + >> Author.find(:all, :include=>{:posts=>:comments}) + => authors + +- posts + +- comments + + # cascaded in two levels and normal association + >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations]) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in two levels with two has_many associations + >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]}) + => authors + +- posts + +- comments + +- categorizations + + # cascaded in three levels + >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}}) + => companies + +- groups + +- members + +- favorites + +* Make counter cache work when replacing an association #3245 *eugenol@gmail.com* + +* Make migrations verbose *Jamis Buck* + +* Make counter_cache work with polymorphic belongs_to *Jamis Buck* + +* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp* + +* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats: + + * Does not support DATE SQL column types; use DATETIME instead. + * Date columns on HABTM join tables are returned as String, not Time. + * Insertions are potentially broken for :polymorphic join tables + * BLOB column access not yet fully supported + +* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper* + +* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper* + +* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen* + +* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson* + +* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes* + +* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark* + +* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net* + +* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney* + +* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward* + +* Added support for nested scopes #3407 [anna@wota.jp]. Examples: + + Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10 + + # inner rule is used. (all previous parameters are ignored) + Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis') + end + + # parameters are merged + Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do + Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10 + end + end + +* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com* + +* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh* + +* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind* + +* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples: + + Person.average :age + Person.minimum :age + Person.maximum :age + Person.sum :salary, :group => :last_name + +* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath* + +* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper* + +* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net* + +* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de* + +* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes* + +* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva* + +* Allow :include to be used with has_many :through associations #3611 *Michael Schoen* + +* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac* + +* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward* + +* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson* + +* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org* + +* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark* + +* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke* + +* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson* + +* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar* + +* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt* + +* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda* + +* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>* + +* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen* + +* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson* + +* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.* + +* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar* + +* Make .count work for has_many associations with multi line finder sql *Michael Schoen* + +* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck* + +* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com* + +* Don't hardcode 'id' in acts as list. *ror@philippeapril.com* + +* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark* + +* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp* + +* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com* + +* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke* + +* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.* + +* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de* + +* Sanitize scoped conditions. *Marcel Molina Jr.* + +* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson* + +* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke* + +* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke* + +* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber* + +* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron* + +* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke* + +* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke* + +* made .find() work on :through relations. *Tobias Lütke* + +* Fix typo in association docs. #3296. *Blair Zajac* + +* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke* + +## 1.13.2 (December 13th, 2005) ## + +* Become part of Rails 1.0 + +* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper* + +* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example: + + class Post + has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author + end + + post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors + post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors + post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors + +* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson* + +* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder* + +* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com* + +* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org* + +* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com* + +* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko* + +* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com* + +* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen* + +* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes* + +* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil* + +* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond* + +* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson* + +* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen* + +* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper* + +* Added preliminary support for polymorphic associations *David Heinemeier Hansson* + +* Added preliminary support for join models *David Heinemeier Hansson* + +* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.* + +* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>* + +* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>* + +* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper* + +* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen* + +* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com* + +* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper* + +* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen* + +* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda* + +* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper* + +* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda* + +* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.* + +* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes* + +* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes* + +* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>* + +* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans* + +* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.* + +* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>* + +* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com* + +* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>* + +* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>* + +* Correct documentation for Base.delete_all. #1568 *Newhydra* + +* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>* + +* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>* + +* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper* + +* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>* + +* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper* + +* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper* + +* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper* + +* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko* + +* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>* + +* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de* + +* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>* + +* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com* + +* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar* + +* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney* + +* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper* + +* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.* + +* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com* + +* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper* + +* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper* + +* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>* + + +## 1.13.0 (November 7th, 2005) ## + +* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko* + +* Added :include as an option for association declarations [David Heinemeier Hansson]. Example: + + has_many :posts, :include => [ :author, :comments ] + +* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example: + + Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do + # Find where name = ? and active=true + Comment.find :all, :conditions => ['name = ?', name] + # Create comment associated with :post_id + Comment.create :body => "Hello world" + end + +* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko* + +* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example: + + Comment.constrain(:creation => { :post_id => 5 }) do + # Associated with :post_id + Comment.create :body => "Hello world" + end + + This is rarely used directly, but allows for find_or_create on associations. So you can do: + + # If the tag doesn't exist, a new one is created that's associated with the person + person.tags.find_or_create_by_name("Summer") + +* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example: + + # No 'Summer' tag exists + Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") + + # Now the 'Summer' tag does exist + Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") + +* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example: + + class Account < ActiveRecord::Base + has_many :people do + def find_or_create_by_name(name) + first_name, *last_name = name.split + last_name = last_name.join " " + + find_or_create_by_first_name_and_last_name(first_name, last_name) + end + end + end + + person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson") + person.first_name # => "David" + person.last_name # => "Heinemeier Hansson" + + Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation). + +* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko* + +* Quote column names in generated SQL. #2728 *Ryan Tomayko* + +* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper* + +* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper* + +* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>* + +* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson* + +* Added migration support for Oracle #2647 *Michael Schoen* + +* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>* + +* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko* + +* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward* + +* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward* + +* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com* + +* Constraints are cloned so they can't be inadvertently modified while they're + in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>] +* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com* + +* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen* + +* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt* + + +## 1.12.2 (October 26th, 2005) ## + +* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark* + +* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>* + +* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes* + +* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>* + +* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>* + +* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>* + + +## 1.12.1 (October 19th, 2005) ## + +* Always parenthesize :conditions options so they may be safely combined with STI and constraints. + +* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com* + +* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations + + +## 1.12.0 (October 16th, 2005) ## + +* Update/clean up documentation (rdoc) + +* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>* + +* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson* + +* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net* + +* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>* + +* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around. + +* Avoid memleak in dev mode when using fcgi + +* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>* + +* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>* + +* Fix errors caused by assigning a has-one or belongs-to property to itself + +* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson* + +* Update DB2 adapter. #2206. *contact@maik-schmidt.de* + +* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com* + +* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency. + +* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>* + +* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code* + +* Add test coverage for content_columns. #2432. *coffee2code* + +* Speed up for unthreaded environments. #2431. *Stefan Kaes* + +* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes* + +* Speed up the setting of table_name. #2428. *Stefan Kaes* + +* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes* + +* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>* + +* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes* + +* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>* + +* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick* + +* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes* + +* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes* + +* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar* + +* Added :force option to create_table that'll try to drop the table if it already exists before creating + +* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar* + +* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>* + +* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>* + +* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman* + +* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>* + +* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>* + +* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>* + +* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>* + +* Make update_attribute use the same writer method that update_attributes uses. + \#2237 [trevor@protocool.com] +* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.* + +* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org* + +* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com* + +* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior) + +* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example: + + ActiveRecord::Base.observers = :cacher, :garbage_collector + +* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com* + +* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck* + +* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck* + +* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck* + +* Fixed migrations for Windows when using more than 10 *David Naseby* + +* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber* + +* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke* + +* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar* + +* Fixed that Observers didn't observe sub-classes #627 *Florian Weber* + +* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.* + +* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae* + +* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber* + +* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil* + +* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com* + +* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg* + +* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward* + +* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code* + +* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net* + +* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/ + +* Make sure the schema_info table is created before querying the current version #1903 + +* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning* + +* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine* + +* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz* + +* Make destroy return self #1913 *Sebastian Kanthak* + +* Fix typo in validations documentation #1938 *court3nay* + +* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org* + +* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky* + +* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com* + +* Fix create_table so that id column is implicitly added *Rick Olson* + +* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798 + +* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798 + +* Fixed the handling of camelCase columns names in Oracle #1798 + +* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798 + +* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798 + +* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke* + + class Comment < AR:B + def self.search(q) + find(:all, :conditions => ["body = ?", q]) + end + end + + class Post < AR:B + has_many :comments + end + + Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi' + + NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as + by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on + details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself + noticed :) + +* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson* + +* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar* + +* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions + +* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt* + +* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes* + + +## 1.11.1 (11 July, 2005) ## + +* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson* + +* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com* + +* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson* + +* Correct reflected table name for singular associations. #1688 *court3nay* + +* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net* + +* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current + +* Added better error message for "packets out of order" #1630 *court3nay* + +* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640 + + +## 1.11.0 (6 July, 2005) ## + +* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar* + +* Changed logging of SQL statements to use the DEBUG level instead of INFO + +* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator. + +* Added callback hooks to association collections #1549 [Florian Weber]. Example: + + class Project + has_and_belongs_to_many :developers, :before_add => :evaluate_velocity + + def evaluate_velocity(developer) + ... + end + end + + ..raising an exception will cause the object not to be added (or removed, with before_remove). + + +* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry* + +* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato* + +* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber* + +* Speed up ActiveRecord#method_missing for the common case (read_attribute). + +* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes* + +* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath* + +* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at* + +* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig* + +* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry* + +* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry* + +* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net* + +* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl* + +* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be: + + Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1' + + ...should instead be: + + Developer.find( + :all, + :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', + :conditions => 'project_id=1' + ) + +* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.* + +* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon* + +* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379 + +* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid* + +* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice + +* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper* + +* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak]. + Example: + + david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")] + david.save + + If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new + project is saved when david.save is called. + + Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do: + + david.project_ids = [1, 5, 7] + +* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com* + +* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke* + +* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org* + +* Corrected @@configurations typo #1410 *david@ruppconsulting.com* + +* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com* + +* Allow before/after update hooks to work on models using optimistic locking + +* Eager loading of dependent has_one associations won't delete the association #1212 + +* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it. + +* Using transactional fixtures now causes the data to be loaded only once. + +* Added fixture accessor methods that can be used when instantiated fixtures are disabled. + + fixtures :web_sites + + def test_something + assert_equal "Ruby on Rails", web_sites(:rubyonrails).name + end + +* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar* + +* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar* + +* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309 + +* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead + +* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples: + + Conditional validations such as the following are made possible: + validates_numericality_of :income, :if => :employed? + + Conditional validations can also solve the salted login generator problem: + validates_confirmation_of :password, :if => :new_password? + + Using blocks: + validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 } + +* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net* + +* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson* + +* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper* + +* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed. + +* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first. + +* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example: + + # SELECT * FROM topics WHERE title IN ('First', 'Second') + Topic.find_all_by_title(["First", "Second"]) + +* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor* + +* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor* + +* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid* + +* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com* + +* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example: + + development: + adapter: postgresql + database: rails_development + host: localhost + username: postgres + password: + encoding: UTF8 + min_messages: ERROR + +* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck* + +* Added validates_exclusion_of as a negative of validates_inclusion_of + +* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls + + +## 1.10.1 (20th April, 2005) ## + +* Fixed frivilous database queries being triggered with eager loading on empty associations and other things + +* Fixed order of loading in eager associations + +* Fixed stray comma when using eager loading and ordering together from has_many associations #1143 + + +## 1.10.0 (19th April, 2005) ## + +* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example: + + for post in Post.find(:all, :limit => 100) + puts "Post: " + post.title + puts "Written by: " + post.author.name + puts "Last comment on: " + post.comments.first.created_on + end + + This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as: + + for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ]) + + ...and the number of database queries needed is now 1. + +* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples: + + Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC") + Person.find(:first, :order => "created_on DESC", :offset => 5) + Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) + Person.find(:all, :offset => 10, :limit => 10) + +* Added acts_as_nested_set #1000 [wschenk]. Introduction: + + This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with + the added feature that you can select the children and all of it's descendants with + a single query. A good use case for this is a threaded post system, where you want + to display every reply to a comment without multiple selects. + +* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas* + +* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com* + +* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com* + +* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com* + +* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher* + +* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle* + +* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com* + +* Added insert_at(position) to acts_as_list #1083 *DeLynnB* + +* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order) + +* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com* + +* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org* + +* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864 + +* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt* + +* Added quoting of column names for fixtures #997 *jcfischer@gmail.com* + +* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis* + +* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes* + +* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org* + +* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper* + +* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org* + +* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes* + +* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes* + +* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas* + +* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias) + + +## 1.9.1 (27th March, 2005) ## + +* Fixed that Active Record objects with float attribute could not be cloned #808 + +* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar* + +* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count + +* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron* + +* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb* + + +## 1.9.0 (22th March, 2005) ## + +* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example: + + Developer.find_all nil, 'id ASC', 5 # return the first five developers + Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward + + This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged. + +* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson* + +* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins* + +* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org* + +* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel* + +* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid* + +* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com* + +* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net* + +* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak* + +* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak* + +* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm* + +* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself + +* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body) + + +## 1.8.0 (7th March, 2005) ## + +* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default) + +* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron* + +* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation: + + * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the + +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ + objects that should be inspected to determine which attributes triggered the errors. + * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. + You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. + +* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k* + +* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper* + +* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example: + + class Account < ActiveRecord::Base + has_one :credit_card, :dependent => true + end + class CreditCard < ActiveRecord::Base + belongs_to :account + end + + account.credit_card # => returns existing credit card, lets say id = 12 + account.credit_card = CreditCard.create("number" => "123") + account.save # => CC with id = 12 is destroyed + + +* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation: + + Validates whether the value of the specified attribute is numeric by trying to convert it to + a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression + <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true). + + class Person < ActiveRecord::Base + validates_numericality_of :value, :on => :create + end + + Configuration options: + * <tt>message</tt> - A custom error message (default is: "is not a number") + * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update) + * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false) + + +* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron* + +* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed) + +* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com* + + +## 1.7.0 (24th February, 2005) ## + +* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck* + +* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes: + + 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple + and safe way of passing table-specific sequence information to the adapter.) + 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to + resort to some hacks to get data converted to Date or Time in Ruby. + If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the + hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time. + This is nasty - but if you use Duck Typing you'll probably not care very much. + In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is + valid - too many databases use DATE for both. + Timezones and sub-second precision on timestamps are not supported. + 3. Default values that are functions (such as "SYSDATE") are not supported. This is a + restriction of the way active record supports default values. + 4. Referential integrity constraints are not fully supported. Under at least + some circumstances, active record appears to delete parent and child records out of + sequence and out of transaction scope. (Or this may just be a problem of test setup.) + + The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/ + +* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke* + +* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm* + +* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka* + +* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar* + +* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com* + +* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au* + +* Fixed that find_by_* would fail when column names had numbers #670 *demetrius* + +* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn* + + 1. Created a new columns method that is much cleaner. + 2. Corrected a problem with the select and select_all methods + that didn't account for the LIMIT clause being passed into raw SQL statements. + 3. Implemented the string_to_time method in order to create proper instances of the time class. + 4. Added logic to the simplified_type method that allows the database to specify the scale of float data. + 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string. + +* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow* + +* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example: + + class Person < ActiveRecord::Base + validates_each :first_name, :last_name do |record, attr| + record.errors.add attr, 'starts with z.' if attr[0] == ?z + end + end + +* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper* + +* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example: + + class Person < ActiveRecord::Base + validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID } + end + +* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates* + +* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example: + + class Project < ActiveRecord::Base + primary_key "sysid" + table_name "XYZ_PROJECT" + inheritance_column { original_inheritance_column + "_id" } + end + +* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu* + + +## 1.6.0 (January 25th, 2005) ## + +* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once. + +* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336 + +* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once. + +* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example + + people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } + Person.update(people.keys, people.values) + +* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron* + +* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat* + +* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius* + +* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper* + +* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson* + +* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson* + +* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not + +* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription + +* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius* + +* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron* + + +## 1.5.1 (January 18th, 2005) ## + +* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates* + +* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle* + + +## 1.5.0 (January 17th, 2005) ## + +* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel* + +* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example: + + class Book < ActiveRecord::Base + has_many :pages + belongs_to :library + + validates_associated :pages, :library + end + +* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition: + + == Unsaved objects and associations + + You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be + aware of, mostly involving the saving of associated objects. + + === One-to-one associations + + * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in + order to update their primary keys - except if the parent object is unsaved (new_record? == true). + * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment + is cancelled. + * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below). + * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does + not save the parent either. + + === Collections + + * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object + (the owner of the collection) is not yet stored in the database. + * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false. + * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below). + * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved. + +* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates* + +* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates* + +* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates* + +* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates* + +* Fixed binary support for PostgreSQL #444 *alex@byzantine.no* + +* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the + collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If + it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, + it'll take one less SELECT query if you use length. + +* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de* + +* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson* + +* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey* + +* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz* + +* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper* + +* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower* + +* Added that Observers can use the observes class method instead of overwriting self.observed_class(). + + Before: + class ListSweeper < ActiveRecord::Base + def self.observed_class() [ List, Item ] + end + + After: + class ListSweeper < ActiveRecord::Base + observes List, Item + end + +* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is + +* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name + +* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag. + + Before: topic.update_attribute(:approved, !approved?) + After : topic.toggle!(:approved) + +* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example: + + page.views # => 1 + page.increment!(:views) # executes an UPDATE statement + page.views # => 2 + + page.increment(:views).increment!(:views) + page.views # => 4 + +* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns. + + +## 1.4.0 (January 4th, 2005) ## + +* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the + record increments the lock_version column and the locking facilities ensure that records instantiated twice + will let the last one saved raise a StaleObjectError if the first was also updated. Example: + + p1 = Person.find(1) + p2 = Person.find(1) + + p1.first_name = "Michael" + p1.save + + p2.first_name = "should fail" + p2.save # Raises a ActiveRecord::StaleObjectError + + You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, + or otherwise apply the business logic needed to resolve the conflict. + + \#384 *Michael Koziarski* + +* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL. + They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name, + Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do + <tt>Person.find_by_user_name(user_name)</tt>. + + It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like + <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing + <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do + <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. + + While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like + <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful, + though, as it's not possible to specify the order in which the objects are returned. + +* Added block-style for callbacks #332 [Jeremy Kemper]. + + Before: + before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" }) + + After: + before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" } + +* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 *Josh Peek* + +* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates + and times from the database. This is set to :local by default. + +* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite. + +* Added the possibility of having objects with acts_as_list created before their scope is available or... + +* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 *Maik Schmidt* + +* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 *DeLynn Barry* + +* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 *Jeremy Kemper* + +* Added HasManyAssociation#count that works like Base#count #413 *intinig* + +* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 *xal* + +* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 *Tobias Lütke* + +* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it. + If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 *Jeremy Kemper* + +* Fixed broken transactions that were actually only running object-level and not db level transactions *andreas* + +* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406 + +* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391 + +* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 *Dmitry V. Sabanin* + + +## 1.3.0 (December 23, 2004) ## + +* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like: + + before: + require_association 'person' + class Employee < Person + end + + after: + class Employee < Person + end + + This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes. + +* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341 + +* Added scope option to validation_uniqueness #349 *Kent Sibilev* + +* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type. + This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100". + +* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil *what-a-day* + +* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case. + This only works for auto-incrementing primary keys called "id" for now #359 *Scott Baron* + +* Added Base#clear_association_cache to empty all the cached associations #347 *Tobias Lütke* + +* Added more informative exceptions in establish_connection #356 *Jeremy Kemper* + +* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise). + + Before: + person.attributes = @params["person"] + person.save + + Now: + person.update_attributes(@params["person"]) + +* Added Base.destroy and Base.delete to remove records without holding a reference to them first. + +* Added that query benchmarking will only happen if its going to be logged anyway #344 + +* Added higher_item and lower_item as public methods for acts_as_list #342 *Tobias Lütke* + +* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 *Jeremy Kemper* + +* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used + the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). *Marten* + +* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins *Anna Lissa Cruz* + +* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction. + If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction + bubble up even when you've dealt with local issues. Closes #231 and #340. + +* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 *dpiddy@gmail.com* + +* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations. + +* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request. + + + +## 1.2.0 ## + +* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable + object. *what-a-day* + + class Person < ActiveRecord::Base + validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!" + validates_inclusion_of :age, :in=>0..99 + end + +* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example: + + class TodoItem < ActiveRecord::Base + acts_as_list :scope => :todo_list_id + belongs_to :todo_list + end + +* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in + categories and the likes. *Tobias Lütke* + +* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names + created_at/created_on or updated_at/updated_on are present. *Tobias Lütke* + +* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place *Tobias Lütke* + +* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all + +* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 *Marten* + +* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere *RedTerror* + +* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example: + + ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'. + This error is raised because the column 'type' is reserved for storing the class in case of inheritance. + Please rename this column if you didn't intend it to be used for storing the inheritance class or + overwrite Company.inheritance_column to use another column for that information. + +* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't + have any magic side effects. + +* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 *mjobin* + +* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples: + + Before: + errors.add(:name, "must be shorter") if name.size > 10 + errors.on(:name) # => "must be shorter" + errors.on("name") # => nil + + After: + errors.add(:name, "must be shorter") if name.size > 10 + errors.on(:name) # => "must be shorter" + errors.on("name") # => "must be shorter" + +* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching + it against the regular expression provided. *Marcel Molina Jr.* + + class Person < ActiveRecord::Base + validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create + end + +* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example: + + Validates that the specified attribute matches the length restrictions supplied in either: + + - configuration[:minimum] + - configuration[:maximum] + - configuration[:is] + - configuration[:within] (aka. configuration[:in]) + + Only one option can be used at a time. + + class Person < ActiveRecord::Base + validates_length_of :first_name, :maximum=>30 + validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind" + validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name" + validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character" + validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me." + end + +* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself. + +* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system. + Useful for making sure that only one user can be named "davidhh". + + class Person < ActiveRecord::Base + validates_uniqueness_of :user_name + end + + When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified + attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself. + + +* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example: + + Model: + class Person < ActiveRecord::Base + validates_confirmation_of :password + end + + View: + <%= password_field "person", "password" %> + <%= password_field "person", "password_confirmation" %> + + The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual. + It exists only as an in-memory variable for validating the password. This check is performed both on create and update. + + +* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example: + + class Person < ActiveRecord::Base + validates_acceptance_of :terms_of_service + end + + The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update. + + NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox. + + +* Added validation macros to make the stackable just like the life cycle callbacks. Examples: + + class Person < ActiveRecord::Base + validate { |record| record.errors.add("name", "too short") unless name.size > 10 } + validate { |record| record.errors.add("name", "too long") unless name.size < 20 } + validate_on_create :validate_password + + private + def validate_password + errors.add("password", "too short") unless password.size > 6 + end + end + +* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples: + + Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20] + Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date] + +* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening + through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer + columns. + +* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient + *Florian Weber* + +* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation: + + <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is + specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM. + +* Fixed that methods wrapped in callbacks still return their original result #260 *Jeremy Kemper* + +* Fixed the Inflector to handle the movie/movies pair correctly #261 *Scott Baron* + +* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example: + + Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }]) + +* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method *Michael Koziarski* + + Before: + find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])] + find_first([ "firm_id = %s", firm_id ])] # unsafe! + + After: + find_first([ "user_name = ? AND password = ?", user_name, password ])] + find_first([ "firm_id = ?", firm_id ])] + +* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information) + +* Fixed fixtures using primary key fields called something else than "id" *dave* + +* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 *HariSeldon* + +* Added reverse order of deleting fixtures, so referential keys can be maintained #247 *Tim Bates* + +* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 *Jeremy Kemper* + +* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable + +* Fixed problems with primary keys and postgresql sequences (#230) *Tim Bates* + +* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development. + This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments. + + NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through + require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the + auto-loading associations. + +* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like: + + david: + id: 1 + name: David + + jamis: + id: 2 + name: Jamis + + <% for digit in 3..10 %> + dev_<%= digit %>: + id: <%= digit %> + name: fixture_<%= digit %> + <% end %> + +* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like: + + fixtures/developers/fixtures.yaml + fixtures/accounts/fixtures.yaml + + ...you now need to do: + + fixtures/developers.yaml + fixtures/accounts.yaml + +* Changed the fixture format from: + + name: david + data: + id: 1 + name: David Heinemeier Hansson + birthday: 1979-10-15 + profession: Systems development + --- + name: steve + data: + id: 2 + name: Steve Ross Kellock + birthday: 1974-09-27 + profession: guy with keyboard + + ...to: + + david: + id: 1 + name: David Heinemeier Hansson + birthday: 1979-10-15 + profession: Systems development + + steve: + id: 2 + name: Steve Ross Kellock + birthday: 1974-09-27 + profession: guy with keyboard + + The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten! + +* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements. + + +## 1.1.0 (34) ## + +* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically + instantiated in instance variables relating to their names using the following style: + + class FixturesTest < Test::Unit::TestCase + fixtures :developers # you can add more with comma separation + + def test_developers + assert_equal 3, @developers.size # the container for all the fixtures is automatically set + assert_kind_of Developer, @david # works like @developers["david"].find + assert_equal "David Heinemeier Hansson", @david.name + end + end + +* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional + attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association + between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back + approach: + + post.categories.push_with_attributes(category, :added_on => Date.today) + post.categories.first.added_on # => Date.today + + NOTE: The categories table doesn't have a added_on column, it's the categories_post join table that does! + +* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations *Jeremy Kemper* + +* Fixed that database passwords couldn't be all numeric *Jeremy Kemper* + +* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly *Jeremy Kemper* + +* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all *Sam Stephenson/Jeremy Kemper* + +* Added that you can pass overlapping ids to find without getting duplicated records back *Jeremy Kemper* + +* Added that Base.benchmark returns the result of the block *Jeremy Kemper* + +* Fixed problem with unit tests on Windows with SQLite *paterno* + +* Fixed that quotes would break regular non-yaml fixtures *Dmitry Sabanin/daft* + +* Fixed fixtures on windows with line endings cause problems under unix / mac *Tobias Lütke* + +* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id + +* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations + +* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records *geech* + +* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete *geech* + +* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create *geech* + +* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works: + + [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] + +* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called + before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations. + +* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates, + which is common on associations that also use metadata. Usage: post.categories.uniq + +* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one + +* Fixed has_and_belongs_to_many to treat associations between classes in modules properly *Florian Weber* + +* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist *geech* + +* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues *geech* + +* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods *geech* + +* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash *geech* + +* Added that any additional fields added to the join table in a has_and_belongs_to_many association + will be placed as attributes when pulling records out through has_and_belongs_to_many associations. + This is helpful when have information about the association itself that you want available on retrival. + +* Added better loading exception catching and RubyGems retries to the database adapters *alexeyv* + +* Fixed bug with per-model transactions *daniel* + +* Fixed Base#transaction so that it returns the result of the last expression in the transaction block *alexeyv* + +* Added Fixture#find to find the record corresponding to the fixture id. The record + class name is guessed by using Inflector#classify (also new) on the fixture directory name. + + Before: Document.find(@documents["first"]["id"]) + After : @documents["first"].find + +* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly *Andreas Schwarz* + +* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM *geech* + +* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete + adapters for a call to the dbm. *Andreas Schwarz* + +* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR. + + +## 1.0.0 (35) ## + +* Added OO-style associations methods [Florian Weber]. Examples: + + Project#milestones_count => Project#milestones.size + Project#build_to_milestones => Project#milestones.build + Project#create_for_milestones => Project#milestones.create + Project#find_in_milestones => Project#milestones.find + Project#find_all_in_milestones => Project#milestones.find_all + +* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated + serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this: + + class User < ActiveRecord::Base + serialize :settings + end + + This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify + an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in + the hierarchy. Example: + + class User < ActiveRecord::Base + serialize :settings, :class_name => "Hash" + end + + user = User.create("settings" => %w( one two three )) + User.find(user.id).settings # => raises SerializationTypeMismatch + +* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class + you want to have connected to another database than Base. This will automatically also connect decendents of that class + to the different database [Renald Buter]. + +* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks + can raise exceptions knowing that the save will be rolled back. *Suggested by Alexey Verkhovsky* + +* Added column name quoting so reserved words, such as "references", can be used as column names *Ryan Platte* + +* Added the possibility to chain the return of what happened inside a logged block [geech]: + + This now works: + log { ... }.map { ... } + + Instead of doing: + result = [] + log { result = ... } + result.map { ... } + +* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" *Anna Lissa Cruz* + +* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema, + person.respond_to? "name" will return true. + +* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block. + Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all): + + Project.benchmark("Creating project") do + project = Project.create("name" => "stuff") + project.create_manager("name" => "David") + project.milestones << Milestone.find_all + end + +* Added logging of invalid SQL statements *Daniel Von Fange* + +* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name *Andreas Schwarz* + +* Added RubyGems require attempt if sqlite-ruby is not available through regular methods. + +* Added compatibility with 2.x series of sqlite-ruby drivers. *Jamis Buck* + +* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to + assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on + mistaken association assignments. *Reported by Andreas Schwarz* + +* Added the option to keep many fixtures in one single YAML document *what-a-day* + +* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing + the type for inheritance hierarchies. *Dave Steinberg* + +* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten *Dave Steinberg* + +* Added the option to observer more than one class at the time by specifying observed_class as an array + +* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them + on PostgreSQL. *Dave Steinberg* + +* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49) + +* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port *Andreas Schwarz* + +* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue. + +* Changed class inheritable attributes to not use eval *Caio Chassot* + +* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those *Marcel Molina Jr.* + +* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) *Marcel Molina Jr.* + +* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed. + +* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter *Andreas Schwarz* + +* Fixed PostgreSQL defaults are now handled gracefully *Dave Steinberg* + +* Fixed increment/decrement_counter are now atomic updates *Andreas Schwarz* + +* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis *radsaq/Florian Gross* + +* Fixed that cloned records would point attribute references on the parent object *Andreas Schwarz* + +* Fixed SQL for type call on inheritance hierarchies *Caio Chassot* + +* Fixed bug with typed inheritance *Florian Weber* + +* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association + + +## 0.9.5 ## + +* Expanded the table_name guessing rules immensely [Florian Green]. Documentation: + + Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending + directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used + to guess the table name from even when called on Reply. The guessing rules are as follows: + * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table. + * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies", + so a Category class becomes a categories table. + * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table. + * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table. + * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table. + * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table. + * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table. + * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table. + * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table. + * Class name ends in an "s": No additional characters are added or removed. + * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table. + * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table. + Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. + So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts". + + You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a + "mice" table. Example: + + class Mouse < ActiveRecord::Base + def self.table_name() "mice" end + end + + This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb. + +* Added find_all_in_collection to has_many defined collections. Works like this: + + class Firm < ActiveRecord::Base + has_many :clients + end + + firm.id # => 1 + firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000 + + *Requested by Dave Thomas* + +* Fixed finders for inheritance hierarchies deeper than one level *Florian Weber* + +* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this: + + class Person < ActiveRecord::Base + protected + def validation + errors.add_on_boundry_breaking "password", 3..20 + end + end + + This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if + the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings. + +* Implemented a clone method that works properly with AR. It returns a clone of the record that + hasn't been assigned an id yet and is treated as a new record. + +* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified *Scott Barron* + +* Fixed that bignums are saved properly instead of attempted to be YAMLized *Andreas Schwartz* + +* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec *Chad Fowler* + +* Fixed a bug with the exclusively_dependent option for has_many + + +## 0.9.4 ## + +* Correctly guesses the primary key when the class is inside a module [Dave Steinberg]. + +* Added [] and []= as alternatives to read_attribute and write_attribute *Dave Steinberg* + +* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq]. + +* The ids passed to find and find_on_conditions are now automatically sanitized. + +* Added escaping of plings in YAML content. + +* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class. + +* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create) + + +## 0.9.3 ## + +* Fixed bug with using a different primary key name together with has_and_belongs_to_many *Investigation by Scott* + +* Added :exclusively_dependent option to the has_many association macro. The doc reads: + + If set to true all the associated object are deleted in one SQL statement without having their + before_destroy callback run. This should only be used on associations that depend solely on + this class and don't need to do any clean-up in before_destroy. The upside is that it's much + faster, especially if there's a counter_cache involved. + +* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server + running on another port than the default. + +* Converted the new natural singleton methods that prevented AR objects from being saved by PStore + (and hence be placed in a Rails session) to a module. *Florian Weber* + +* Fixed the use of floats (was broken since 0.9.0+) + +* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with + Action Pack scaffolding. + +* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) *radsaq* + + +## 0.9.2 ## + +* Added static method for instantly updating a record + +* Treat decimal and numeric as Ruby floats *Andreas Schwartz* + +* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too) + +* Removed debugging output accidently left in (which would screw web applications) + + +## 0.9.1 ## + +* Added MIT license + +* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model: + + class Event < ActiveRecord::Base + has_one_and_belongs_to_many :sponsors + end + + class Sponsor < ActiveRecord::Base + has_one_and_belongs_to_many :sponsors + end + + Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class: + + roskilde_festival.add_to_sponsors(carlsberg) + roskilde_festival.remove_from_sponsors(carlsberg) + + nike.add_to_events(world_cup) + nike.remove_from_events(world_cup) + + Now you can use regular array-styled methods: + + roskilde_festival.sponsors << carlsberg + roskilde_festival.sponsors.delete(carlsberg) + + nike.events << world_cup + nike.events.delete(world_cup) + +* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging + object by setting the foreign key to null. Consider this model: + + class Post < ActiveRecord::Base + has_many :comments + end + + class Comment < ActiveRecord::Base + belongs_to :post + end + + You could do something like: + + funny_comment.has_post? # => true + announcement.comments.delete(funny_comment) + funny_comment.has_post? # => false + + +## 0.9.0 ## + +* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications) + *Implementation idea by Michael Neumann, debugging assistance by Jamis Buck* + +* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute. + This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%. + Done by doing lazy type conversions and caching column information on the class-level. + +* Added callback objects and procs as options for implementing the target for callback macros. + +* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider: + + class Post < ActiveRecord::Base + has_many :comments + end + + class Comment < ActiveRecord::Base + belongs_to :post + end + + Iterating over 100 posts like this: + + <% for post in @posts %> + <%= post.title %> has <%= post.comments_count %> comments + <% end %> + + Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column + to the posts table and rewrite the comments association macro with: + + class Comment < ActiveRecord::Base + belongs_to :post, :counter_cache => true + end + + Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life + with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify + :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another), + you'll have to manage the counter yourself. + +* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model: + + class Project < ActiveRecord::Base + has_one :manager + end + + class Manager < ActiveRecord::Base + belongs_to :project + end + + Earlier, assignments would work like following regardless of which way the assignment told the best story: + + active_record.manager_id = david.id + + Now you can do it either from the belonging side: + + david.project = active_record + + ...or from the having side: + + active_record.manager = david + + If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the + project_id attribute on david would be set to the id of active_record, then david would be saved. + +* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model: + + class Project < ActiveRecord::Base + has_many :milestones + end + + class Milestone < ActiveRecord::Base + belongs_to :project + end + + Earlier, assignments would work like following regardless of which way the assignment told the best story: + + deadline.project_id = active_record.id + + Now you can do it either from the belonging side: + + deadline.project = active_record + + ...or from the having side: + + active_record.milestones << deadline + + The milestone is automatically saved with the new foreign key. + +* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using + to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time). + Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header. + This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do: + + user = User.find(1) + user.preferences = { "background" => "black", "display" => large } + user.save + + User.find(1).preferences # => { "background" => "black", "display" => large } + + Please note that this method should only be used when you don't care about representing the object in proper columns in + the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through + aggregations than this new option. + +* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash + directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement + new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this: + + class Song < ActiveRecord::Base + # Uses an integer of seconds to hold the length of the song + + def length=(minutes) + write_attribute("length", minutes * 60) + end + + def length + read_attribute("length") / 60 + end + end + + The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly. + This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think + you know what you're doing and aren't afraid of future consequences, this is an option. + +* Applied a few minor bug fixes reported by Daniel Von Fange. + + +## 0.8.4 ## + + _Reflection_ +* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations. + +* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects. + +* Added Base#attribute_names which returns an array of names for the attributes available on the object. + +* Added Base#column_for_attribute(name) which returns the column description object for the named attribute. + + + _Misc_ +* Added multi-parameter assignment: + + # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done + # by calling new on the column type or aggregation type (through composed_of) object with these parameters. + # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate + # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the + # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float, + # s for String, and a for Array. + + This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day. + +* Fixed bug with custom primary key column name and Base.find on multiple parameters. + +* Fixed bug with dependent option on has_one associations if there was no associated object. + + +## 0.8.3 ## + + _Transactions_ +* Added transactional protection for destroy (important for the new :dependent option) *Suggested by Carl Youngblood* + +* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions) + +* Changed transactions so only exceptions will cause a rollback, not returned false. + + + _Mapping_ +* Added support for non-integer primary keys *Aredridel/earlier work by Michael Neumann* + + User.find "jdoe" + Product.find "PDKEY-INT-12" + +* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either + be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key + of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id". + +* Added an overwriteable primary_key method that'll instruct AR to the name of the + id column *Aredridele/earlier work by Guan Yang* + + class Project < ActiveRecord::Base + def self.primary_key() "project_id" end + end + +* Fixed that Active Records can safely associate inside and out of modules. + + class MyApplication::Account < ActiveRecord::Base + has_many :clients # will look for MyApplication::Client + has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest + end + +* Fixed that Active Records can safely live inside modules *Aredridel* + + class MyApplication::Account < ActiveRecord::Base + end + + + _Misc_ +* Added freeze call to value object assignments to ensure they remain immutable *Spotted by Gavin Sinclair* + +* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is + observed_class() class method. This is more consistant with things like self.table_name(). Works like this: + + class AuditObserver < ActiveRecord::Observer + def self.observed_class() Account end + def after_update(account) + AuditTrail.new(account, "UPDATED") + end + end + + *Suggested by Gavin Sinclair* + +* Create new Active Record objects by setting the attributes through a block. Like this: + + person = Person.new do |p| + p.name = 'Freddy' + p.age = 19 + end + + *Suggested by Gavin Sinclair* + + +## 0.8.2 ## + +* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are + run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback + method: + + class Topic < ActiveRecord::Base + before_destroy :destroy_author, 'puts "I'm an inline fragment"' + end + + Learn more in link:classes/ActiveRecord/Callbacks.html + +* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when + the holder is destroyed: + + class Album < ActiveRecord::Base + has_many :tracks, :dependent => true + end + + All the associated tracks are destroyed when the album is. + +* Added Base.create as a factory that'll create, save, and return a new object in one step. + +* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you + to pass the argument hashes directly from yaml. (Luke) + +* Fixed the install.rb to include simple.rb *Spotted by Kevin Bullock* + +* Modified block syntax to better follow our code standards outlined in + http://www.rubyonrails.org/CodingStandards + + +## 0.8.1 ## + +* Added object-level transactions *Austin Ziegler* + +* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection, + which is parametized through a config hash with symbol keys instead of a regular parameter list. + This will allow for database connections to be opened in a more generic fashion. (Luke) + + NOTE: This requires all *_connections to be updated! Read more in: + http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081 + +* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes + (t.name is now name). *Spotted by Garrett Rooney* + +* Fixed SQLite adapter so dates are returned as Date objects, not Time objects *Spotted by Gavin Sinclair* + +* Fixed requirement of date class, so date conversions are succesful regardless of whether you + manually require date or not. + + +## 0.8.0 ## + +* Added transactions + +* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7]) + as parameter and then return an array of objects instead of just an object + +* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a + collection, not an association + +* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type + aren't treated as current time *Spotted by Gavin Sinclair* + + +## 0.7.6 ## + +* Fixed the install.rb to create the lib/active_record/support directory *Spotted by Gavin Sinclair* +* Fixed that has_association? would always return true *Daniel Von Fange* diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc index b5db57569c..6f9f63ceee 100644 --- a/activerecord/README.rdoc +++ b/activerecord/README.rdoc @@ -150,7 +150,7 @@ A short rundown of some of the major features: * Database agnostic schema management with Migrations. class AddSystemSettings < ActiveRecord::Migration - def self.up + def up create_table :system_settings do |t| t.string :name t.string :label @@ -162,7 +162,7 @@ A short rundown of some of the major features: SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1 end - def self.down + def down drop_table :system_settings end end @@ -208,7 +208,9 @@ Source code can be downloaded as part of the Rails project on GitHub == License -Active Record is released under the MIT license. +Active Record is released under the MIT license: + +* http://www.opensource.org/licenses/MIT == Support diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 2de81c31a3..4a889c1340 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -7,13 +7,13 @@ Gem::Specification.new do |s| s.summary = 'Object-relational mapper framework (part of Rails).' s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.' - s.required_ruby_version = '>= 1.8.7' + s.required_ruby_version = '>= 1.9.3' s.author = 'David Heinemeier Hansson' s.email = 'david@loudthinking.com' s.homepage = 'http://www.rubyonrails.org' - s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*'] + s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*'] s.require_path = 'lib' s.extra_rdoc_files = %w( README.rdoc ) @@ -21,6 +21,6 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('arel', '~> 2.2.1') + s.add_dependency('arel', '~> 3.0.0.rc1') s.add_dependency('tzinfo', '~> 0.3.29') end diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb index 63822731d5..31f3e02bb8 100644 --- a/activerecord/examples/performance.rb +++ b/activerecord/examples/performance.rb @@ -1,6 +1,6 @@ TIMES = (ENV['N'] || 10000).to_i -require 'rubygems' +require File.expand_path('../../../load_paths', __FILE__) require "active_record" conn = { :adapter => 'sqlite3', :database => ':memory:' } @@ -29,6 +29,14 @@ class Exhibit < ActiveRecord::Base def look; attributes end def feel; look; user.name end + def self.with_name + where("name IS NOT NULL") + end + + def self.with_notes + where("notes IS NOT NULL") + end + def self.look(exhibits) exhibits.each { |e| e.look } end def self.feel(exhibits) exhibits.each { |e| e.feel } end end @@ -37,7 +45,14 @@ puts 'Generating data...' module ActiveRecord class Faker - LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. Praesent varius tincidunt commodo".split + LOREM = %Q{Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. + Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. + Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, + tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, + varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum + tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. + Praesent varius tincidunt commodo}.split + def self.name LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join ' ' end @@ -102,6 +117,10 @@ Benchmark.bm(46) do |x| TIMES.times { Exhibit.first.look } end + x.report 'Model.named_scope' do + TIMES.times { Exhibit.limit(10).with_name.with_notes } + end + x.report("Model.all limit(100) (x#{(TIMES / 10).ceil})") do (TIMES / 10).ceil.times { Exhibit.look Exhibit.limit(100) } end diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 132dc12680..4f194cb6cf 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -39,6 +39,7 @@ module ActiveRecord autoload :Aggregations autoload :Associations autoload :AttributeMethods + autoload :AttributeAssignment autoload :AutosaveAssociation autoload :Relation @@ -50,30 +51,45 @@ module ActiveRecord autoload :PredicateBuilder autoload :SpawnMethods autoload :Batches + autoload :Explain + autoload :Delegation end autoload :Base autoload :Callbacks + autoload :Core autoload :CounterCache + autoload :ConnectionHandling + autoload :DynamicMatchers autoload :DynamicFinderMatch autoload :DynamicScopeMatch + autoload :Explain + autoload :IdentityMap + autoload :Inheritance + autoload :Integration autoload :Migration autoload :Migrator, 'active_record/migration' - autoload :NamedScope + autoload :Model + autoload :ModelSchema autoload :NestedAttributes autoload :Observer autoload :Persistence autoload :QueryCache + autoload :Querying + autoload :ReadonlyAttributes autoload :Reflection autoload :Result + autoload :Sanitization autoload :Schema autoload :SchemaDumper + autoload :Scoping autoload :Serialization autoload :SessionStore + autoload :Store autoload :Timestamp autoload :Transactions + autoload :Translation autoload :Validations - autoload :IdentityMap end module Coders @@ -91,6 +107,7 @@ module ActiveRecord autoload :Read autoload :TimeZoneConversion autoload :Write + autoload :Serialization end end @@ -112,6 +129,15 @@ module ActiveRecord end end + module Scoping + extend ActiveSupport::Autoload + + eager_autoload do + autoload :Named + autoload :Default + end + end + autoload :TestCase autoload :TestFixtures, 'active_record/fixtures' end diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index 81ddbba51e..5a8addc4e4 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -172,8 +172,8 @@ module ActiveRecord # with this option. # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value # object. Each mapping is represented as an array where the first item is the name of the - # entity attribute and the second item is the name the attribute in the value object. The - # order in which mappings are defined determine the order in which attributes are sent to the + # entity attribute and the second item is the name of the attribute in the value object. The + # order in which mappings are defined determines the order in which attributes are sent to the # value class constructor. # * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all @@ -191,7 +191,8 @@ module ActiveRecord # # Option examples: # composed_of :temperature, :mapping => %w(reading celsius) - # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money } + # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), + # :converter => Proc.new { |balance| balance.to_money } # composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ] # composed_of :gps_location # composed_of :gps_location, :allow_nil => true diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 0952ea2829..0efa111d12 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -70,7 +70,7 @@ module ActiveRecord end end - class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc + class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc: def initialize(owner, reflection) super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.") end @@ -196,6 +196,26 @@ module ActiveRecord # * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt> # <tt>Project#categories.delete(category1)</tt> # + # === Overriding generated methods + # + # Association methods are generated in a module that is included into the model class, + # which allows you to easily override with your own methods and call the original + # generated method with +super+. For example: + # + # class Car < ActiveRecord::Base + # belongs_to :owner + # belongs_to :old_owner + # def owner=(new_owner) + # self.old_owner = self.owner + # super + # end + # end + # + # If your model class is <tt>Project</tt>, the module is + # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is + # included in the model class immediately after the (anonymous) generated attributes methods + # module, meaning an association will override the methods for an attribute with the same name. + # # === A word of warning # # Don't create associations that have the same name as instance methods of @@ -1165,7 +1185,7 @@ module ActiveRecord # has_many :subscribers, :through => :subscriptions, :source => :user # has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new { # %Q{ - # SELECT DISTINCT people.* + # SELECT DISTINCT * # FROM people p, post_subscriptions ps # WHERE ps.post_id = #{id} AND ps.person_id = p.id # ORDER BY p.first_name @@ -1424,18 +1444,18 @@ module ActiveRecord # join table with a migration such as this: # # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration - # def self.up + # def change # create_table :developers_projects, :id => false do |t| # t.integer :developer_id # t.integer :project_id # end # end - # - # def self.down - # drop_table :developers_projects - # end # end # + # It's also a good idea to add indexes to each of those columns to speed up the joins process. + # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only + # uses one index per table during the lookup. + # # Adds the following methods for retrieval and query: # # [collection(force_reload = false)] diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index d1e3ff8e38..7887d59aad 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -231,10 +231,7 @@ module ActiveRecord def build_record(attributes, options) reflection.build_association(attributes, options) do |record| - record.assign_attributes( - create_scope.except(*record.changed), - :without_protection => true - ) + record.assign_attributes(create_scope.except(*record.changed), :without_protection => true) end end end diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index 6cc401e6cc..090f690f0d 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -20,31 +20,19 @@ module ActiveRecord # It's okay to just apply all these like this. The options will only be present if the # association supports that option; this is enforced by the association builder. scope = scope.apply_finder_options(options.slice( - :readonly, :include, :order, :limit, :joins, :group, :having, :offset)) + :readonly, :include, :eager_load, :order, :limit, :joins, :group, :having, :offset, :select)) if options[:through] && !options[:include] scope = scope.includes(source_options[:include]) end - if select = select_value - scope = scope.select(select) - end + scope = scope.uniq if options[:uniq] add_constraints(scope) end private - def select_value - select_value = options[:select] - - if reflection.collection? - select_value ||= options[:uniq] && "DISTINCT #{reflection.quoted_table_name}.*" - end - - select_value - end - def add_constraints(scope) tables = construct_tables diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb index 96fca97440..776f0d0469 100644 --- a/activerecord/lib/active_record/associations/builder/association.rb +++ b/activerecord/lib/active_record/associations/builder/association.rb @@ -1,7 +1,7 @@ module ActiveRecord::Associations::Builder class Association #:nodoc: class_attribute :valid_options - self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate] + self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :eager_load, :extend, :readonly, :validate] # Set by subclasses class_attribute :macro @@ -16,6 +16,10 @@ module ActiveRecord::Associations::Builder @model, @name, @options = model, name, options end + def mixin + @model.generated_feature_methods + end + def build validate_options reflection = model.create_reflection(self.class.macro, name, options, model) @@ -36,16 +40,14 @@ module ActiveRecord::Associations::Builder def define_readers name = self.name - - model.redefine_method(name) do |*params| + mixin.redefine_method(name) do |*params| association(name).reader(*params) end end def define_writers name = self.name - - model.redefine_method("#{name}=") do |value| + mixin.redefine_method("#{name}=") do |value| association(name).writer(value) end end diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index f6d26840c2..1759a41d93 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -25,14 +25,14 @@ module ActiveRecord::Associations::Builder name = self.name method_name = "belongs_to_counter_cache_after_create_for_#{name}" - model.redefine_method(method_name) do + mixin.redefine_method(method_name) do record = send(name) record.class.increment_counter(cache_column, record.id) unless record.nil? end model.after_create(method_name) method_name = "belongs_to_counter_cache_before_destroy_for_#{name}" - model.redefine_method(method_name) do + mixin.redefine_method(method_name) do record = send(name) record.class.decrement_counter(cache_column, record.id) unless record.nil? end @@ -48,7 +48,7 @@ module ActiveRecord::Associations::Builder method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}" touch = options[:touch] - model.redefine_method(method_name) do + mixin.redefine_method(method_name) do record = send(name) unless record.nil? diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb index f62209a226..35f9a3ae8e 100644 --- a/activerecord/lib/active_record/associations/builder/collection_association.rb +++ b/activerecord/lib/active_record/associations/builder/collection_association.rb @@ -58,7 +58,7 @@ module ActiveRecord::Associations::Builder super name = self.name - model.redefine_method("#{name.to_s.singularize}_ids") do + mixin.redefine_method("#{name.to_s.singularize}_ids") do association(name).ids_reader end end @@ -67,7 +67,7 @@ module ActiveRecord::Associations::Builder super name = self.name - model.redefine_method("#{name.to_s.singularize}_ids=") do |ids| + mixin.redefine_method("#{name.to_s.singularize}_ids=") do |ids| association(name).ids_writer(ids) end end diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index 30fc44b4c2..0b634ab944 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -18,7 +18,7 @@ module ActiveRecord::Associations::Builder model.send(:include, Module.new { class_eval <<-RUBY, __FILE__, __LINE__ + 1 def destroy_associations - association(#{name.to_sym.inspect}).delete_all + association(#{name.to_sym.inspect}).delete_all_on_destroy super end RUBY diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb index ecbc70888f..9c24f40690 100644 --- a/activerecord/lib/active_record/associations/builder/has_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_many.rb @@ -28,7 +28,7 @@ module ActiveRecord::Associations::Builder def define_destroy_dependency_method name = self.name - model.send(:define_method, dependency_method_name) do + mixin.redefine_method(dependency_method_name) do send(name).each do |o| # No point in executing the counter update since we're going to destroy the parent anyway counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym @@ -45,15 +45,21 @@ module ActiveRecord::Associations::Builder def define_delete_all_dependency_method name = self.name - model.send(:define_method, dependency_method_name) do + mixin.redefine_method(dependency_method_name) do + association(name).delete_all_on_destroy + end + end + + def define_nullify_dependency_method + name = self.name + mixin.redefine_method(dependency_method_name) do send(name).delete_all end end - alias :define_nullify_dependency_method :define_delete_all_dependency_method def define_restrict_dependency_method name = self.name - model.send(:define_method, dependency_method_name) do + mixin.redefine_method(dependency_method_name) do raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty? end end diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb index 88c0d3e90f..7a6cd3890f 100644 --- a/activerecord/lib/active_record/associations/builder/has_one.rb +++ b/activerecord/lib/active_record/associations/builder/has_one.rb @@ -44,18 +44,17 @@ module ActiveRecord::Associations::Builder end def define_destroy_dependency_method - model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1) - def #{dependency_method_name} - association(#{name.to_sym.inspect}).delete - end - eoruby + name = self.name + mixin.redefine_method(dependency_method_name) do + association(name).delete + end end alias :define_delete_dependency_method :define_destroy_dependency_method alias :define_nullify_dependency_method :define_destroy_dependency_method def define_restrict_dependency_method name = self.name - model.redefine_method(dependency_method_name) do + mixin.redefine_method(dependency_method_name) do raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).nil? end end diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb index 0cbbba041a..436b6c1524 100644 --- a/activerecord/lib/active_record/associations/builder/singular_association.rb +++ b/activerecord/lib/active_record/associations/builder/singular_association.rb @@ -16,15 +16,15 @@ module ActiveRecord::Associations::Builder def define_constructors name = self.name - model.redefine_method("build_#{name}") do |*params, &block| + mixin.redefine_method("build_#{name}") do |*params, &block| association(name).build(*params, &block) end - model.redefine_method("create_#{name}") do |*params, &block| + mixin.redefine_method("create_#{name}") do |*params, &block| association(name).create(*params, &block) end - model.redefine_method("create_#{name}!") do |*params, &block| + mixin.redefine_method("create_#{name}!") do |*params, &block| association(name).create!(*params, &block) end end diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index cec876149c..fe9f30bd2a 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -49,10 +49,18 @@ module ActiveRecord end else column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}" + relation = scoped - scoped.select(column).map! do |record| - record.send(reflection.association_primary_key) + including = (relation.eager_load_values + relation.includes_values).uniq + + if including.any? + join_dependency = ActiveRecord::Associations::JoinDependency.new(reflection.klass, including, []) + relation = join_dependency.join_associations.inject(relation) do |r, association| + association.join_relation(r) + end end + + relation.uniq.pluck(column) end end @@ -152,6 +160,13 @@ module ActiveRecord end end + # Called when the association is declared as :dependent => :delete_all. This is + # an optimised version which avoids loading the records into memory. Not really + # for public consumption. + def delete_all_on_destroy + scoped.delete_all + end + # Destroy all the records from this association. # # See destroy for more info. @@ -235,7 +250,7 @@ module ActiveRecord # This method is abstract in the sense that it relies on # +count_records+, which is a method descendants have to provide. def size - if owner.new_record? || (loaded? && !options[:uniq]) + if !find_target? || (loaded? && !options[:uniq]) target.size elsif !loaded? && options[:group] load_target.size @@ -344,8 +359,12 @@ module ActiveRecord if options[:counter_sql] interpolate(options[:counter_sql]) else - # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */ - interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" } + # replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */ + interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do + count_with = $2.to_s + count_with = '*' if count_with.blank? || count_with =~ /,/ + "SELECT #{$1}COUNT(#{count_with}) FROM" + end end end diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 3181ca9a32..eb320bc774 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -39,10 +39,9 @@ module ActiveRecord instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to|proxy_/ } delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, - :lock, :readonly, :having, :to => :scoped + :lock, :readonly, :having, :pluck, :to => :scoped - delegate :target, :load_target, :loaded?, :scoped, - :to => :@association + delegate :target, :load_target, :loaded?, :to => :@association delegate :select, :find, :first, :last, :build, :create, :create!, @@ -62,6 +61,13 @@ module ActiveRecord @association end + def scoped + association = @association + association.scoped.extending do + define_method(:proxy_association) { association } + end + end + def respond_to?(name, include_private = false) super || (load_target && target.respond_to?(name, include_private)) || diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index 1f917f58f2..a4cea99372 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -32,6 +32,10 @@ module ActiveRecord record end + # ActiveRecord::Relation#delete_all needs to support joins before we can use a + # SQL-only implementation. + alias delete_all_on_destroy delete_all + private def count_records diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 50ee60284c..059e6c77bc 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -99,6 +99,10 @@ module ActiveRecord end end end + + def foreign_key_present? + owner.attribute_present?(reflection.association_primary_key) + end end end end diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 2e818dca5d..9657cb081d 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -6,6 +6,13 @@ module ActiveRecord class HasManyThroughAssociation < HasManyAssociation #:nodoc: include ThroughAssociation + def initialize(owner, reflection) + super + + @through_records = {} + @through_association = nil + end + # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been # loaded and calling collection.size if it has. If it's more likely than not that the collection does # have a size larger than zero, and you need to fetch that collection afterwards, it'll take one fewer @@ -42,27 +49,40 @@ module ActiveRecord end end - through_record(record).save! + save_through_record(record) update_counter(1) record end - private + # ActiveRecord::Relation#delete_all needs to support joins before we can use a + # SQL-only implementation. + alias delete_all_on_destroy delete_all - def through_record(record) - through_association = owner.association(through_reflection.name) - attributes = construct_join_attributes(record) + private - through_record = Array.wrap(through_association.target).find { |candidate| - candidate.attributes.slice(*attributes.keys) == attributes - } + def through_association + @through_association ||= owner.association(through_reflection.name) + end - unless through_record - through_record = through_association.build(attributes) + # We temporarily cache through record that has been build, because if we build a + # through record in build_record and then subsequently call insert_record, then we + # want to use the exact same object. + # + # However, after insert_record has been called, we clear the cache entry because + # we want it to be possible to have multiple instances of the same record in an + # association + def build_through_record(record) + @through_records[record.object_id] ||= begin + through_record = through_association.build(construct_join_attributes(record)) through_record.send("#{source_reflection.name}=", record) + through_record end + end - through_record + def save_through_record(record) + build_through_record(record).save! + ensure + @through_records.delete(record.object_id) end def build_record(attributes, options = {}) @@ -73,9 +93,9 @@ module ActiveRecord inverse = source_reflection.inverse_of if inverse if inverse.macro == :has_many - record.send(inverse.name) << through_record(record) + record.send(inverse.name) << build_through_record(record) elsif inverse.macro == :has_one - record.send("#{inverse.name}=", through_record(record)) + record.send("#{inverse.name}=", build_through_record(record)) end end @@ -104,8 +124,7 @@ module ActiveRecord def delete_records(records, method) ensure_not_nested - through = owner.association(through_reflection.name) - scope = through.scoped.where(construct_join_attributes(*records)) + scope = through_association.scoped.where(construct_join_attributes(*records)) case method when :destroy @@ -116,7 +135,7 @@ module ActiveRecord count = scope.delete_all end - delete_through_records(through, records) + delete_through_records(records) if through_reflection.macro == :has_many && update_through_counter?(method) update_counter(-count, through_reflection) @@ -125,15 +144,25 @@ module ActiveRecord update_counter(-count) end - def delete_through_records(through, records) - if through_reflection.macro == :has_many - records.each do |record| - through.target.delete(through_record(record)) - end - else - records.each do |record| - through.target = nil if through.target == through_record(record) + def through_records_for(record) + attributes = construct_join_attributes(record) + candidates = Array.wrap(through_association.target) + candidates.find_all { |c| c.attributes.slice(*attributes.keys) == attributes } + end + + def delete_through_records(records) + records.each do |record| + through_records = through_records_for(record) + + if through_reflection.macro == :has_many + through_records.each { |r| through_association.target.delete(r) } + else + if through_records.include?(through_association.target) + through_association.target = nil + end end + + @through_records.delete(record.object_id) end end diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index 6c878f0f00..827b01c5ac 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -184,7 +184,7 @@ module ActiveRecord macro = join_part.reflection.macro if macro == :has_one - return if record.association_cache.key?(join_part.reflection.name) + return record.association(join_part.reflection.name).target if record.association_cache.key?(join_part.reflection.name) association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil? set_target_and_inverse(join_part, association, record) else diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 779f8164cc..298decb0f1 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -100,6 +100,7 @@ module ActiveRecord scope = scope.select(preload_options[:select] || options[:select] || table[Arel.star]) scope = scope.includes(preload_options[:include] || options[:include]) + scope = scope.eager_load(preload_options[:eager_load] || options[:eager_load]) if options[:as] scope = scope.where( diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb index ad6374d09a..97898c53ae 100644 --- a/activerecord/lib/active_record/associations/preloader/through_association.rb +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -53,6 +53,7 @@ module ActiveRecord else if options[:conditions] through_options[:include] = options[:include] || options[:source] + through_options[:eager_load] = options[:eager_load] || options[:source] through_options[:conditions] = options[:conditions] end diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb index b347a94978..f95e5337c2 100644 --- a/activerecord/lib/active_record/associations/through_association.rb +++ b/activerecord/lib/active_record/associations/through_association.rb @@ -44,7 +44,7 @@ module ActiveRecord join_attributes = { source_reflection.foreign_key => records.map { |record| - record.send(source_reflection.association_primary_key) + record.send(source_reflection.association_primary_key(reflection.klass)) } } diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb new file mode 100644 index 0000000000..bf9fe70b31 --- /dev/null +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -0,0 +1,221 @@ +require 'active_support/concern' + +module ActiveRecord + module AttributeAssignment + extend ActiveSupport::Concern + include ActiveModel::MassAssignmentSecurity + + module ClassMethods + private + + # The primary key and inheritance column can never be set by mass-assignment for security reasons. + def attributes_protected_by_default + default = [ primary_key, inheritance_column ] + default << 'id' unless primary_key.eql? 'id' + default + end + end + + # Allows you to set all the attributes at once by passing in a hash with keys + # matching the attribute names (which again matches the column names). + # + # If any attributes are protected by either +attr_protected+ or + # +attr_accessible+ then only settable attributes will be assigned. + # + # class User < ActiveRecord::Base + # attr_protected :is_admin + # end + # + # user = User.new + # user.attributes = { :username => 'Phusion', :is_admin => true } + # user.username # => "Phusion" + # user.is_admin? # => false + def attributes=(new_attributes) + return unless new_attributes.is_a?(Hash) + + assign_attributes(new_attributes) + end + + # Allows you to set all the attributes for a particular mass-assignment + # security role by passing in a hash of attributes with keys matching + # the attribute names (which again matches the column names) and the role + # name using the :as option. + # + # To bypass mass-assignment security you can use the :without_protection => true + # option. + # + # class User < ActiveRecord::Base + # attr_accessible :name + # attr_accessible :name, :is_admin, :as => :admin + # end + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }) + # user.name # => "Josh" + # user.is_admin? # => false + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin) + # user.name # => "Josh" + # user.is_admin? # => true + # + # user = User.new + # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true) + # user.name # => "Josh" + # user.is_admin? # => true + def assign_attributes(new_attributes, options = {}) + return unless new_attributes + + attributes = new_attributes.stringify_keys + multi_parameter_attributes = [] + nested_parameter_attributes = [] + @mass_assignment_options = options + + unless options[:without_protection] + attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role) + end + + attributes.each do |k, v| + if k.include?("(") + multi_parameter_attributes << [ k, v ] + elsif respond_to?("#{k}=") + if v.is_a?(Hash) + nested_parameter_attributes << [ k, v ] + else + send("#{k}=", v) + end + else + raise(UnknownAttributeError, "unknown attribute: #{k}") + end + end + + # assign any deferred nested attributes after the base attributes have been set + nested_parameter_attributes.each do |k,v| + send("#{k}=", v) + end + + @mass_assignment_options = nil + assign_multiparameter_attributes(multi_parameter_attributes) + end + + protected + + def mass_assignment_options + @mass_assignment_options ||= {} + end + + def mass_assignment_role + mass_assignment_options[:as] || :default + end + + private + + # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done + # by calling new on the column type or aggregation type (through composed_of) object with these parameters. + # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate + # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the + # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, + # f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the + # attribute will be set to nil. + def assign_multiparameter_attributes(pairs) + execute_callstack_for_multiparameter_attributes( + extract_callstack_for_multiparameter_attributes(pairs) + ) + end + + def instantiate_time_object(name, values) + if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name)) + Time.zone.local(*values) + else + Time.time_with_datetime_fallback(self.class.default_timezone, *values) + end + end + + def execute_callstack_for_multiparameter_attributes(callstack) + errors = [] + callstack.each do |name, values_with_empty_parameters| + begin + send(name + "=", read_value_from_parameter(name, values_with_empty_parameters)) + rescue => ex + errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name}", ex, name) + end + end + unless errors.empty? + raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes" + end + end + + def read_value_from_parameter(name, values_hash_from_param) + klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass + if values_hash_from_param.values.all?{|v|v.nil?} + nil + elsif klass == Time + read_time_parameter_value(name, values_hash_from_param) + elsif klass == Date + read_date_parameter_value(name, values_hash_from_param) + else + read_other_parameter_value(klass, name, values_hash_from_param) + end + end + + def read_time_parameter_value(name, values_hash_from_param) + # If Date bits were not provided, error + raise "Missing Parameter" if [1,2,3].any?{|position| !values_hash_from_param.has_key?(position)} + max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param, 6) + # If Date bits were provided but blank, then return nil + return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} + + set_values = (1..max_position).collect{|position| values_hash_from_param[position] } + # If Time bits are not there, then default to 0 + (3..5).each {|i| set_values[i] = set_values[i].blank? ? 0 : set_values[i]} + instantiate_time_object(name, set_values) + end + + def read_date_parameter_value(name, values_hash_from_param) + return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} + set_values = [values_hash_from_param[1], values_hash_from_param[2], values_hash_from_param[3]] + begin + Date.new(*set_values) + rescue ArgumentError # if Date.new raises an exception on an invalid date + instantiate_time_object(name, set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates + end + end + + def read_other_parameter_value(klass, name, values_hash_from_param) + max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param) + values = (1..max_position).collect do |position| + raise "Missing Parameter" if !values_hash_from_param.has_key?(position) + values_hash_from_param[position] + end + klass.new(*values) + end + + def extract_max_param_for_multiparameter_attributes(values_hash_from_param, upper_cap = 100) + [values_hash_from_param.keys.max,upper_cap].min + end + + def extract_callstack_for_multiparameter_attributes(pairs) + attributes = { } + + pairs.each do |pair| + multiparameter_name, value = pair + attribute_name = multiparameter_name.split("(").first + attributes[attribute_name] = {} unless attributes.include?(attribute_name) + + parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) + attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value + end + + attributes + end + + def type_cast_attribute_value(multiparameter_name, value) + multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value + end + + def find_parameter_position(multiparameter_name) + multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i + end + + end +end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index d7bfaa5655..c5834e2fef 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -7,35 +7,53 @@ module ActiveRecord extend ActiveSupport::Concern include ActiveModel::AttributeMethods + included do + include Read + include Write + include BeforeTypeCast + include Query + include PrimaryKey + include TimeZoneConversion + include Dirty + include Serialization + + # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, + # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). + # (Alias for the protected read_attribute method). + alias [] read_attribute + + # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. + # (Alias for the protected write_attribute method). + alias []= write_attribute + + public :[], :[]= + end + module ClassMethods # Generates all the attribute related methods for columns in the database # accessors, mutators and query methods. def define_attribute_methods return if attribute_methods_generated? - - if base_class == self - super(column_names) - @attribute_methods_generated = true - else - base_class.define_attribute_methods - end + superclass.define_attribute_methods unless self == base_class + super(column_names) + @attribute_methods_generated = true end def attribute_methods_generated? - if base_class == self - @attribute_methods_generated ||= false - else - base_class.attribute_methods_generated? - end + @attribute_methods_generated ||= false end - def undefine_attribute_methods(*args) - if base_class == self - super - @attribute_methods_generated = false - else - base_class.undefine_attribute_methods(*args) - end + # We will define the methods as instance methods, but will call them as singleton + # methods. This allows us to use method_defined? to check if the method exists, + # which is fast and won't give any false positives from the ancestors (because + # there are no ancestors). + def generated_external_attribute_methods + @generated_external_attribute_methods ||= Module.new { extend self } + end + + def undefine_attribute_methods + super if attribute_methods_generated? + @attribute_methods_generated = false end def instance_method_already_implemented?(method_name) @@ -43,19 +61,46 @@ module ActiveRecord raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord" end - super + if [Base, Model].include?(active_record_super) + super + else + # If B < A and A defines its own attribute method, then we don't want to overwrite that. + defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods) + defined && !ActiveRecord::Base.method_defined?(method_name) || super + end end # A method name is 'dangerous' if it is already defined by Active Record, but # not by any ancestors. (So 'puts' is not dangerous but 'save' is.) - def dangerous_attribute_method?(method_name) - active_record = ActiveRecord::Base - superclass = ActiveRecord::Base.superclass - - (active_record.method_defined?(method_name) || - active_record.private_method_defined?(method_name)) && - !superclass.method_defined?(method_name) && - !superclass.private_method_defined?(method_name) + def dangerous_attribute_method?(name) + method_defined_within?(name, Base) + end + + def method_defined_within?(name, klass, sup = klass.superclass) + if klass.method_defined?(name) || klass.private_method_defined?(name) + if sup.method_defined?(name) || sup.private_method_defined?(name) + klass.instance_method(name).owner != sup.instance_method(name).owner + else + true + end + else + false + end + end + + def attribute_method?(attribute) + super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ''))) + end + + # Returns an array of column names as strings if it's not + # an abstract class and table exists. + # Otherwise it returns an empty array. + def attribute_names + @attribute_names ||= if !abstract_class? && table_exists? + column_names + else + [] + end end end @@ -94,9 +139,105 @@ module ActiveRecord super end + # Returns true if the given attribute is in the attributes hash + def has_attribute?(attr_name) + @attributes.has_key?(attr_name.to_s) + end + + # Returns an array of names for the attributes available on this object. + def attribute_names + @attributes.keys + end + + # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. + def attributes + Hash[@attributes.map { |name, _| [name, read_attribute(name)] }] + end + + # Returns an <tt>#inspect</tt>-like string for the value of the + # attribute +attr_name+. String attributes are truncated upto 50 + # characters, and Date and Time attributes are returned in the + # <tt>:db</tt> format. Other attributes return the value of + # <tt>#inspect</tt> without modification. + # + # person = Person.create!(:name => "David Heinemeier Hansson " * 3) + # + # person.attribute_for_inspect(:name) + # # => '"David Heinemeier Hansson David Heinemeier Hansson D..."' + # + # person.attribute_for_inspect(:created_at) + # # => '"2009-01-12 04:48:57"' + def attribute_for_inspect(attr_name) + value = read_attribute(attr_name) + + if value.is_a?(String) && value.length > 50 + "#{value[0..50]}...".inspect + elsif value.is_a?(Date) || value.is_a?(Time) + %("#{value.to_s(:db)}") + else + value.inspect + end + end + + # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither + # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings). + def attribute_present?(attribute) + value = read_attribute(attribute) + !value.nil? || (value.respond_to?(:empty?) && !value.empty?) + end + + # Returns the column object for the named attribute. + def column_for_attribute(name) + self.class.columns_hash[name.to_s] + end + protected - def attribute_method?(attr_name) - attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_name)) + + def clone_attributes(reader_method = :read_attribute, attributes = {}) + attribute_names.each do |name| + attributes[name] = clone_attribute_value(reader_method, name) end + attributes + end + + def clone_attribute_value(reader_method, attribute_name) + value = send(reader_method, attribute_name) + value.duplicable? ? value.clone : value + rescue TypeError, NoMethodError + value + end + + # Returns a copy of the attributes hash where all the values have been safely quoted for use in + # an Arel insert/update method. + def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys) + attrs = {} + klass = self.class + arel_table = klass.arel_table + + attribute_names.each do |name| + if (column = column_for_attribute(name)) && (include_primary_key || !column.primary) + + if include_readonly_attributes || !self.class.readonly_attributes.include?(name) + + value = if klass.serialized_attributes.include?(name) + @attributes[name].serialized_value + else + # FIXME: we need @attributes to be used consistently. + # If the values stored in @attributes were already type + # casted, this code could be simplified + read_attribute(name) + end + + attrs[arel_table[name]] = value + end + end + end + + attrs + end + + def attribute_method?(attr_name) + attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_name)) + end end end diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 3eff3d54e3..40e4a97e73 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -13,7 +13,7 @@ module ActiveRecord raise "You cannot include Dirty after Timestamp" end - class_attribute :partial_updates + config_attribute :partial_updates self.partial_updates = true end @@ -34,9 +34,9 @@ module ActiveRecord @previously_changed = changes @changed_attributes.clear end - rescue - IdentityMap.remove(self) if IdentityMap.enabled? - raise + rescue + IdentityMap.remove(self) if IdentityMap.enabled? + raise end # <tt>reload</tt> the record and clears changed attributes. diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 36d7f4ad11..a7785f8786 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -5,16 +5,48 @@ module ActiveRecord # Returns this record's primary key value wrapped in an Array if one is available def to_key - key = send(self.class.primary_key) + key = self.id [key] if key end + # Returns the primary key value + def id + read_attribute(self.class.primary_key) + end + + # Sets the primary key value + def id=(value) + write_attribute(self.class.primary_key, value) + end + + # Queries the primary key value + def id? + query_attribute(self.class.primary_key) + end + module ClassMethods + def define_method_attribute(attr_name) + super + + if attr_name == primary_key && attr_name != 'id' + generated_attribute_methods.send(:alias_method, :id, primary_key) + generated_external_attribute_methods.module_eval <<-CODE, __FILE__, __LINE__ + def id(v, attributes, attributes_cache, attr_name) + attr_name = '#{primary_key}' + send(attr_name, attributes[attr_name], attributes, attributes_cache, attr_name) + end + CODE + end + end + + def dangerous_attribute_method?(method_name) + super && !['id', 'id=', 'id?'].include?(method_name) + end + # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the # primary_key_prefix_type setting, though. def primary_key - @primary_key ||= reset_primary_key - raise ActiveRecord::UnknownPrimaryKey.new(self) unless @primary_key + @primary_key = reset_primary_key unless defined? @primary_key @primary_key end @@ -24,16 +56,11 @@ module ActiveRecord end def reset_primary_key #:nodoc: - key = self == base_class ? get_primary_key(base_class.name) : - base_class.primary_key - - set_primary_key(key) - key - end - - def primary_key? #:nodoc: - @primary_key ||= reset_primary_key - !@primary_key.nil? + if self == base_class + self.primary_key = get_primary_key(base_class.name) + else + self.primary_key = base_class.primary_key + end end def get_primary_key(base_name) #:nodoc: @@ -45,35 +72,32 @@ module ActiveRecord when :table_name_with_underscore base_name.foreign_key else - if ActiveRecord::Base != self && connection.table_exists?(table_name) - connection.primary_key(table_name) + if ActiveRecord::Base != self && table_exists? + connection.schema_cache.primary_keys[table_name] else 'id' end end end - attr_accessor :original_primary_key - - # Attribute writer for the primary key column - def primary_key=(value) - @quoted_primary_key = nil - @primary_key = value - end - - # Sets the name of the primary key column to use to the given value, - # or (if the value is nil or false) to the value returned by the given - # block. + # Sets the name of the primary key column. + # + # class Project < ActiveRecord::Base + # self.primary_key = "sysid" + # end + # + # You can also define the primary_key method yourself: # # class Project < ActiveRecord::Base - # set_primary_key "sysid" + # def self.primary_key + # "foo_" + super + # end # end - def set_primary_key(value = nil, &block) - @quoted_primary_key = nil - @primary_key ||= '' - self.original_primary_key = @primary_key - value &&= value.to_s - self.primary_key = block_given? ? instance_eval(&block) : value + # Project.primary_key # => "foo_id" + def primary_key=(value) + @original_primary_key = @primary_key if defined?(@primary_key) + @primary_key = value && value.to_s + @quoted_primary_key = nil end end end diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index 8566ecad14..964c4123ef 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -6,11 +6,8 @@ module ActiveRecord ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date] included do - cattr_accessor :attribute_types_cached_by_default, :instance_writer => false + config_attribute :attribute_types_cached_by_default, :global => true self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT - - # Undefine id so it can be used as an attribute name - undef_method(:id) if method_defined?(:id) end module ClassMethods @@ -32,107 +29,101 @@ module ActiveRecord cached_attributes.include?(attr_name) end + def undefine_attribute_methods + generated_external_attribute_methods.module_eval do + instance_methods.each { |m| undef_method(m) } + end + + super + end + + def type_cast_attribute(attr_name, attributes, cache = {}) #:nodoc: + return unless attr_name + attr_name = attr_name.to_s + + if generated_external_attribute_methods.method_defined?(attr_name) + if attributes.has_key?(attr_name) || attr_name == 'id' + generated_external_attribute_methods.send(attr_name, attributes[attr_name], attributes, cache, attr_name) + end + elsif !attribute_methods_generated? + # If we haven't generated the caster methods yet, do that and + # then try again + define_attribute_methods + type_cast_attribute(attr_name, attributes, cache) + else + # If we get here, the attribute has no associated DB column, so + # just return it verbatim. + attributes[attr_name] + end + end + protected + # We want to generate the methods via module_eval rather than define_method, + # because define_method is slower on dispatch and uses more memory (because it + # creates a closure). + # + # But sometimes the database might return columns with characters that are not + # allowed in normal method names (like 'my_column(omg)'. So to work around this + # we first define with the __temp__ identifier, and then use alias method to + # rename it to what we want. def define_method_attribute(attr_name) - if serialized_attributes.include?(attr_name) - define_read_method_for_serialized_attribute(attr_name) - else - define_read_method(attr_name, attr_name, columns_hash[attr_name]) - end + cast_code = attribute_cast_code(attr_name) - if primary_key? && attr_name == primary_key && attr_name != "id" - define_read_method('id', attr_name, columns_hash[attr_name]) - end + generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + def __temp__ + #{internal_attribute_access_code(attr_name, cast_code)} + end + alias_method '#{attr_name}', :__temp__ + undef_method :__temp__ + STR + + generated_external_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + def __temp__(v, attributes, attributes_cache, attr_name) + #{external_attribute_access_code(attr_name, cast_code)} + end + alias_method '#{attr_name}', :__temp__ + undef_method :__temp__ + STR end private def cacheable_column?(column) - serialized_attributes.include?(column.name) || attribute_types_cached_by_default.include?(column.type) - end - - # Define read method for serialized attribute. - def define_read_method_for_serialized_attribute(attr_name) - access_code = "@attributes_cache['#{attr_name}'] ||= @attributes['#{attr_name}']" - generated_attribute_methods.module_eval("def _#{attr_name}; #{access_code}; end; alias #{attr_name} _#{attr_name}", __FILE__, __LINE__) + attribute_types_cached_by_default.include?(column.type) end - # Define an attribute reader method. Cope with nil column. - # method_name is the same as attr_name except when a non-standard primary key is used, - # we still define #id as an accessor for the key - def define_read_method(method_name, attr_name, column) - cast_code = column.type_cast_code('v') - access_code = "(v=@attributes['#{attr_name}']) && #{cast_code}" + def internal_attribute_access_code(attr_name, cast_code) + access_code = "(v=@attributes[attr_name]) && #{cast_code}" - unless primary_key? && attr_name.to_s == primary_key.to_s - access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ") + unless attr_name == primary_key + access_code.insert(0, "missing_attribute(attr_name, caller) unless @attributes.has_key?(attr_name); ") end if cache_attribute?(attr_name) - access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})" + access_code = "@attributes_cache[attr_name] ||= (#{access_code})" end - # Where possible, generate the method by evalling a string, as this will result in - # faster accesses because it avoids the block eval and then string eval incurred - # by the second branch. - # - # The second, slower, branch is necessary to support instances where the database - # returns columns with extra stuff in (like 'my_column(omg)'). - if method_name =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ - def _#{method_name} - #{access_code} - end - - alias #{method_name} _#{method_name} - STR - else - generated_attribute_methods.module_eval do - define_method("_#{method_name}") { eval(access_code) } - alias_method(method_name, "_#{method_name}") - end - end + "attr_name = '#{attr_name}'; #{access_code}" end - end - # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, - # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). - def read_attribute(attr_name) - method = "_#{attr_name}" - if respond_to? method - send method if @attributes.has_key?(attr_name.to_s) - else - _read_attribute attr_name - end - end + def external_attribute_access_code(attr_name, cast_code) + access_code = "v && #{cast_code}" - def _read_attribute(attr_name) - attr_name = attr_name.to_s - attr_name = self.class.primary_key? && self.class.primary_key if attr_name == 'id' - value = @attributes[attr_name] - unless value.nil? - if column = column_for_attribute(attr_name) - if unserializable_attribute?(attr_name, column) - unserialize_attribute(attr_name) - else - column.type_cast(value) + if cache_attribute?(attr_name) + access_code = "attributes_cache[attr_name] ||= (#{access_code})" end - else - value + + access_code end - end - end - # Returns true if the attribute is of a text column and marked for serialization. - def unserializable_attribute?(attr_name, column) - column.text? && self.class.serialized_attributes.include?(attr_name) + def attribute_cast_code(attr_name) + columns_hash[attr_name].type_cast_code('v') + end end - # Returns the unserialized object of the attribute. - def unserialize_attribute(attr_name) - coder = self.class.serialized_attributes[attr_name] - unserialized_object = coder.load(@attributes[attr_name]) - - @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object + # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, + # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). + def read_attribute(attr_name) + self.class.type_cast_attribute(attr_name, @attributes, @attributes_cache) end private diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb new file mode 100644 index 0000000000..0c8e4e4b9a --- /dev/null +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -0,0 +1,93 @@ +module ActiveRecord + module AttributeMethods + module Serialization + extend ActiveSupport::Concern + + included do + # Returns a hash of all the attributes that have been specified for serialization as + # keys and their class restriction as values. + config_attribute :serialized_attributes + self.serialized_attributes = {} + end + + class Attribute < Struct.new(:coder, :value, :state) + def unserialized_value + state == :serialized ? unserialize : value + end + + def serialized_value + state == :unserialized ? serialize : value + end + + def unserialize + self.state = :unserialized + self.value = coder.load(value) + end + + def serialize + self.state = :serialized + self.value = coder.dump(value) + end + end + + module ClassMethods + # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, + # then specify the name of that attribute using this method and it will be handled automatically. + # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that + # class on retrieval or SerializationTypeMismatch will be raised. + # + # ==== Parameters + # + # * +attr_name+ - The field name that should be serialized. + # * +class_name+ - Optional, class name that the object type should be equal to. + # + # ==== Example + # # Serialize a preferences attribute + # class User < ActiveRecord::Base + # serialize :preferences + # end + def serialize(attr_name, class_name = Object) + coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) } + class_name + else + Coders::YAMLColumn.new(class_name) + end + + # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy + # has its own hash of own serialized attributes + self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder) + end + + def initialize_attributes(attributes) #:nodoc: + super + + serialized_attributes.each do |key, coder| + if attributes.key?(key) + attributes[key] = Attribute.new(coder, attributes[key], :serialized) + end + end + + attributes + end + + private + + def attribute_cast_code(attr_name) + if serialized_attributes.include?(attr_name) + "v.unserialized_value" + else + super + end + end + end + + def type_cast_attribute_for_write(column, value) + if column && coder = self.class.serialized_attributes[column.name] + Attribute.new(coder, value, :unserialized) + else + super + end + end + end + end +end diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb index 62a3cfa9a5..2f86e32f41 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -7,30 +7,25 @@ module ActiveRecord extend ActiveSupport::Concern included do - cattr_accessor :time_zone_aware_attributes, :instance_writer => false + config_attribute :time_zone_aware_attributes, :global => true self.time_zone_aware_attributes = false - class_attribute :skip_time_zone_conversion_for_attributes, :instance_writer => false + config_attribute :skip_time_zone_conversion_for_attributes self.skip_time_zone_conversion_for_attributes = [] end module ClassMethods protected - # Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled. - # This enhanced read method automatically converts the UTC time stored in the database to the time + # The enhanced read method automatically converts the UTC time stored in the database to the time # zone stored in Time.zone. - def define_method_attribute(attr_name) - if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name]) - method_body, line = <<-EOV, __LINE__ + 1 - def _#{attr_name} - cached = @attributes_cache['#{attr_name}'] - return cached if cached - time = _read_attribute('#{attr_name}') - @attributes_cache['#{attr_name}'] = time.acts_like?(:time) ? time.in_time_zone : time - end - alias #{attr_name} _#{attr_name} - EOV - generated_attribute_methods.module_eval(method_body, __FILE__, line) + def attribute_cast_code(attr_name) + column = columns_hash[attr_name] + + if create_time_zone_conversion_attribute?(attr_name, column) + typecast = "v = #{super}" + time_zone_conversion = "v.acts_like?(:time) ? v.in_time_zone : v" + + "((#{typecast}) && (#{time_zone_conversion}))" else super end diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb index 4db6d71ba6..fde55b95da 100644 --- a/activerecord/lib/active_record/attribute_methods/write.rb +++ b/activerecord/lib/active_record/attribute_methods/write.rb @@ -10,17 +10,13 @@ module ActiveRecord module ClassMethods protected def define_method_attribute=(attr_name) - if attr_name =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP + if attr_name =~ ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__) else generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value| write_attribute(attr_name, new_value) end end - - if primary_key? && attr_name == primary_key && attr_name != "id" - generated_attribute_methods.module_eval("alias :id= :'#{primary_key}='") - end end end @@ -32,10 +28,8 @@ module ActiveRecord @attributes_cache.delete(attr_name) column = column_for_attribute(attr_name) - if column && column.number? - @attributes[attr_name] = convert_number_column_value(value) - elsif column || @attributes.has_key?(attr_name) - @attributes[attr_name] = value + if column || @attributes.has_key?(attr_name) + @attributes[attr_name] = type_cast_attribute_for_write(column, value) else raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'" end @@ -47,6 +41,26 @@ module ActiveRecord def attribute=(attribute_name, value) write_attribute(attribute_name, value) end + + def type_cast_attribute_for_write(column, value) + if column && column.number? + convert_number_column_value(value) + else + value + end + end + + def convert_number_column_value(value) + if value == false + 0 + elsif value == true + 1 + elsif value.is_a?(String) && value.blank? + nil + else + value + end + end end end end diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 056170d82a..c86eaba498 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -21,6 +21,21 @@ module ActiveRecord # Note that <tt>:autosave => false</tt> is not same as not declaring <tt>:autosave</tt>. # When the <tt>:autosave</tt> option is not present new associations are saved. # + # == Validation + # + # Children records are validated unless <tt>:validate</tt> is +false+. + # + # == Callbacks + # + # Association with autosave option defines several callbacks on your + # model (before_save, after_create, after_update). Please note that + # callbacks are executed in the order they were defined in + # model. You should avoid modyfing the association content, before + # autosave callbacks are executed. Placing your callbacks after + # associations is usually a good practice. + # + # == Examples + # # === One-to-one Example # # class Post @@ -109,10 +124,7 @@ module ActiveRecord # Now it _is_ removed from the database: # # Comment.find_by_id(id).nil? # => true - # - # === Validation - # - # Children records are validated unless <tt>:validate</tt> is +false+. + module AutosaveAssociation extend ActiveSupport::Concern @@ -264,7 +276,7 @@ module ActiveRecord # turned on for the association. def validate_single_association(reflection) association = association_instance_get(reflection.name) - record = association && association.target + record = association && association.reader association_valid?(reflection, record) if record end @@ -331,7 +343,7 @@ module ActiveRecord if autosave saved = association.insert_record(record, false) else - association.insert_record(record) + association.insert_record(record) unless reflection.nested? end elsif autosave saved = record.save(:validate => false) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 137b4c6534..d29cf82dad 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -23,9 +23,11 @@ require 'active_support/core_ext/module/delegation' require 'active_support/core_ext/module/introspection' require 'active_support/core_ext/object/duplicable' require 'active_support/core_ext/object/blank' +require 'active_support/deprecation' require 'arel' require 'active_record/errors' require 'active_record/log_subscriber' +require 'active_record/explain_subscriber' module ActiveRecord #:nodoc: # = Active Record @@ -115,8 +117,8 @@ module ActiveRecord #:nodoc: # When joining tables, nested hashes or keys written in the form 'table_name.column_name' # can be used to qualify the table name of a particular condition. For instance: # - # Student.joins(:schools).where(:schools => { :type => 'public' }) - # Student.joins(:schools).where('schools.type' => 'public' ) + # Student.joins(:schools).where(:schools => { :category => 'public' }) + # Student.joins(:schools).where('schools.category' => 'public' ) # # == Overwriting default accessors # @@ -325,1843 +327,8 @@ module ActiveRecord #:nodoc: # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all # instances in the current object space. class Base - ## - # :singleton-method: - # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, - # which is then passed on to any new database connections made and which can be retrieved on both - # a class and instance level by calling +logger+. - cattr_accessor :logger, :instance_writer => false - - ## - # :singleton-method: - # Contains the database configuration - as is typically stored in config/database.yml - - # as a Hash. - # - # For example, the following database.yml... - # - # development: - # adapter: sqlite3 - # database: db/development.sqlite3 - # - # production: - # adapter: sqlite3 - # database: db/production.sqlite3 - # - # ...would result in ActiveRecord::Base.configurations to look like this: - # - # { - # 'development' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/development.sqlite3' - # }, - # 'production' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/production.sqlite3' - # } - # } - cattr_accessor :configurations, :instance_writer => false - @@configurations = {} - - ## - # :singleton-method: - # Accessor for the prefix type that will be prepended to every primary key column name. - # The options are :table_name and :table_name_with_underscore. If the first is specified, - # the Product class will look for "productid" instead of "id" as the primary column. If the - # latter is specified, the Product class will look for "product_id" instead of "id". Remember - # that this is a global setting for all Active Records. - cattr_accessor :primary_key_prefix_type, :instance_writer => false - @@primary_key_prefix_type = nil - - ## - # :singleton-method: - # Accessor for the name of the prefix string to prepend to every table name. So if set - # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people", - # etc. This is a convenient way of creating a namespace for tables in a shared database. - # By default, the prefix is the empty string. - # - # If you are organising your models within modules you can add a prefix to the models within - # a namespace by defining a singleton method in the parent module called table_name_prefix which - # returns your chosen prefix. - class_attribute :table_name_prefix, :instance_writer => false - self.table_name_prefix = "" - - ## - # :singleton-method: - # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", - # "people_basecamp"). By default, the suffix is the empty string. - class_attribute :table_name_suffix, :instance_writer => false - self.table_name_suffix = "" - - ## - # :singleton-method: - # Indicates whether table names should be the pluralized versions of the corresponding class names. - # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. - # See table_name for the full rules on table/class naming. This is true, by default. - class_attribute :pluralize_table_names, :instance_writer => false - self.pluralize_table_names = true - - ## - # :singleton-method: - # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling - # dates and times from the database. This is set to :local by default. - cattr_accessor :default_timezone, :instance_writer => false - @@default_timezone = :local - - ## - # :singleton-method: - # Specifies the format to use when dumping the database schema with Rails' - # Rakefile. If :sql, the schema is dumped as (potentially database- - # specific) SQL statements. If :ruby, the schema is dumped as an - # ActiveRecord::Schema file which can be loaded into any database that - # supports migrations. Use :ruby if you want to have different database - # adapters for, e.g., your development and test environments. - cattr_accessor :schema_format , :instance_writer => false - @@schema_format = :ruby - - ## - # :singleton-method: - # Specify whether or not to use timestamps for migration versions - cattr_accessor :timestamped_migrations , :instance_writer => false - @@timestamped_migrations = true - - # Determine whether to store the full constant name including namespace when using STI - class_attribute :store_full_sti_class - self.store_full_sti_class = true - - # Stores the default scope for the class - class_attribute :default_scopes, :instance_writer => false - self.default_scopes = [] - - # Returns a hash of all the attributes that have been specified for serialization as - # keys and their class restriction as values. - class_attribute :serialized_attributes - self.serialized_attributes = {} - - class_attribute :_attr_readonly, :instance_writer => false - self._attr_readonly = [] - - class << self # Class methods - delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped - delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped - delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped - delegate :find_each, :find_in_batches, :to => :scoped - delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped - delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped - - # Executes a custom SQL query against your database and returns all the results. The results will - # be returned as an array with columns requested encapsulated as attributes of the model you call - # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in - # a Product object with the attributes you specified in the SQL query. - # - # If you call a complicated SQL query which spans multiple tables the columns specified by the - # SELECT will be attributes of the model, whether or not they are columns of the corresponding - # table. - # - # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be - # no database agnostic conversions performed. This should be a last resort because using, for example, - # MySQL specific terms will lock you to using that particular database engine or require you to - # change your call if you switch engines. - # - # ==== Examples - # # A simple SQL query spanning multiple tables - # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" - # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] - # - # # You can use the same string replacement techniques as you can with ActiveRecord#find - # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] - # > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...] - def find_by_sql(sql, binds = []) - connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) } - end - - # Creates an object (or multiple objects) and saves it to the database, if validations pass. - # The resulting object is returned whether the object was saved successfully to the database or not. - # - # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the - # attributes on the objects that are to be created. - # - # +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options - # in the +options+ parameter. - # - # ==== Examples - # # Create a single new object - # User.create(:first_name => 'Jamie') - # - # # Create a single new object using the :admin mass-assignment security role - # User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) - # - # # Create a single new object bypassing mass-assignment security - # User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) - # - # # Create an Array of new objects - # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) - # - # # Create a single object and pass it into a block to set other attributes. - # User.create(:first_name => 'Jamie') do |u| - # u.is_admin = false - # end - # - # # Creating an Array of new objects using a block, where the block is executed for each object: - # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u| - # u.is_admin = false - # end - def create(attributes = nil, options = {}, &block) - if attributes.is_a?(Array) - attributes.collect { |attr| create(attr, options, &block) } - else - object = new(attributes, options, &block) - object.save - object - end - end - - # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. - # The use of this method should be restricted to complicated SQL queries that can't be executed - # using the ActiveRecord::Calculations class methods. Look into those before using this. - # - # ==== Parameters - # - # * +sql+ - An SQL statement which should return a count query from the database, see the example below. - # - # ==== Examples - # - # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" - def count_by_sql(sql) - sql = sanitize_conditions(sql) - connection.select_value(sql, "#{name} Count").to_i - end - - # Attributes listed as readonly will be used to create a new record but update operations will - # ignore these fields. - def attr_readonly(*attributes) - self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || []) - end - - # Returns an array of all the attributes that have been specified as readonly. - def readonly_attributes - self._attr_readonly - end - - # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, - # then specify the name of that attribute using this method and it will be handled automatically. - # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that - # class on retrieval or SerializationTypeMismatch will be raised. - # - # ==== Parameters - # - # * +attr_name+ - The field name that should be serialized. - # * +class_name+ - Optional, class name that the object type should be equal to. - # - # ==== Example - # # Serialize a preferences attribute - # class User < ActiveRecord::Base - # serialize :preferences - # end - def serialize(attr_name, class_name = Object) - coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) } - class_name - else - Coders::YAMLColumn.new(class_name) - end - - # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy - # has its own hash of own serialized attributes - self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder) - end - - # Guesses the table name (in forced lower-case) based on the name of the class in the - # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy - # looks like: Reply < Message < ActiveRecord::Base, then Message is used - # to guess the table name even when called on Reply. The rules used to do the guess - # are handled by the Inflector class in Active Support, which knows almost all common - # English inflections. You can add new inflections in config/initializers/inflections.rb. - # - # Nested classes are given table names prefixed by the singular form of - # the parent's table name. Enclosing modules are not considered. - # - # ==== Examples - # - # class Invoice < ActiveRecord::Base - # end - # - # file class table_name - # invoice.rb Invoice invoices - # - # class Invoice < ActiveRecord::Base - # class Lineitem < ActiveRecord::Base - # end - # end - # - # file class table_name - # invoice.rb Invoice::Lineitem invoice_lineitems - # - # module Invoice - # class Lineitem < ActiveRecord::Base - # end - # end - # - # file class table_name - # invoice/lineitem.rb Invoice::Lineitem lineitems - # - # Additionally, the class-level +table_name_prefix+ is prepended and the - # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, - # the table name guess for an Invoice class becomes "myapp_invoices". - # Invoice::Lineitem becomes "myapp_invoice_lineitems". - # - # You can also overwrite this class method to allow for unguessable - # links, such as a Mouse class with a link to a "mice" table. Example: - # - # class Mouse < ActiveRecord::Base - # set_table_name "mice" - # end - def table_name - reset_table_name - end - - # Returns a quoted version of the table name, used to construct SQL statements. - def quoted_table_name - @quoted_table_name ||= connection.quote_table_name(table_name) - end - - # Computes the table name, (re)sets it internally, and returns it. - def reset_table_name #:nodoc: - return if abstract_class? - - self.table_name = compute_table_name - end - - def full_table_name_prefix #:nodoc: - (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix - end - - # Defines the column name for use with single table inheritance. Use - # <tt>set_inheritance_column</tt> to set a different value. - def inheritance_column - @inheritance_column ||= "type" - end - - # Lazy-set the sequence name to the connection's default. This method - # is only ever called once since set_sequence_name overrides it. - def sequence_name #:nodoc: - reset_sequence_name - end - - def reset_sequence_name #:nodoc: - default = connection.default_sequence_name(table_name, primary_key) - set_sequence_name(default) - default - end - - # Sets the table name. If the value is nil or false then the value returned by the given - # block is used. - # - # class Project < ActiveRecord::Base - # set_table_name "project" - # end - def set_table_name(value = nil, &block) - @quoted_table_name = nil - define_attr_method :table_name, value, &block - @arel_table = nil - - @relation = Relation.new(self, arel_table) - end - alias :table_name= :set_table_name - - # Sets the name of the inheritance column to use to the given value, - # or (if the value # is nil or false) to the value returned by the - # given block. - # - # class Project < ActiveRecord::Base - # set_inheritance_column do - # original_inheritance_column + "_id" - # end - # end - def set_inheritance_column(value = nil, &block) - define_attr_method :inheritance_column, value, &block - end - alias :inheritance_column= :set_inheritance_column - - # Sets the name of the sequence to use when generating ids to the given - # value, or (if the value is nil or false) to the value returned by the - # given block. This is required for Oracle and is useful for any - # database which relies on sequences for primary key generation. - # - # If a sequence name is not explicitly set when using Oracle or Firebird, - # it will default to the commonly used pattern of: #{table_name}_seq - # - # If a sequence name is not explicitly set when using PostgreSQL, it - # will discover the sequence corresponding to your primary key for you. - # - # class Project < ActiveRecord::Base - # set_sequence_name "projectseq" # default would have been "project_seq" - # end - def set_sequence_name(value = nil, &block) - define_attr_method :sequence_name, value, &block - end - alias :sequence_name= :set_sequence_name - - # Indicates whether the table associated with this class exists - def table_exists? - connection.table_exists?(table_name) - end - - # Returns an array of column objects for the table associated with this class. - def columns - if defined?(@primary_key) - connection_pool.primary_keys[table_name] ||= @primary_key - end - - connection_pool.columns[table_name] - end - - # Returns a hash of column objects for the table associated with this class. - def columns_hash - connection_pool.columns_hash[table_name] - end - - # Returns a hash where the keys are column names and the values are - # default values when instantiating the AR object for this table. - def column_defaults - connection_pool.column_defaults[table_name] - end - - # Returns an array of column names as strings. - def column_names - @column_names ||= columns.map { |column| column.name } - end - - # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", - # and columns used for single table inheritance have been removed. - def content_columns - @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } - end - - # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key - # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute - # is available. - def column_methods_hash #:nodoc: - @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr| - attr_name = attr.to_s - methods[attr.to_sym] = attr_name - methods["#{attr}=".to_sym] = attr_name - methods["#{attr}?".to_sym] = attr_name - methods["#{attr}_before_type_cast".to_sym] = attr_name - methods - end - end - - # Resets all the cached information about columns, which will cause them - # to be reloaded on the next request. - # - # The most common usage pattern for this method is probably in a migration, - # when just after creating a table you want to populate it with some default - # values, eg: - # - # class CreateJobLevels < ActiveRecord::Migration - # def self.up - # create_table :job_levels do |t| - # t.integer :id - # t.string :name - # - # t.timestamps - # end - # - # JobLevel.reset_column_information - # %w{assistant executive manager director}.each do |type| - # JobLevel.create(:name => type) - # end - # end - # - # def self.down - # drop_table :job_levels - # end - # end - def reset_column_information - connection.clear_cache! - undefine_attribute_methods - connection_pool.clear_table_cache!(table_name) if table_exists? - - @column_names = @content_columns = @dynamic_methods_hash = @inheritance_column = nil - @arel_engine = @relation = nil - end - - def clear_cache! # :nodoc: - connection_pool.clear_cache! - end - - def attribute_method?(attribute) - super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ''))) - end - - # Returns an array of column names as strings if it's not - # an abstract class and table exists. - # Otherwise it returns an empty array. - def attribute_names - @attribute_names ||= if !abstract_class? && table_exists? - column_names - else - [] - end - end - - # Set the lookup ancestors for ActiveModel. - def lookup_ancestors #:nodoc: - klass = self - classes = [klass] - return classes if klass == ActiveRecord::Base - - while klass != klass.base_class - classes << klass = klass.superclass - end - classes - end - - # Set the i18n scope to overwrite ActiveModel. - def i18n_scope #:nodoc: - :activerecord - end - - # True if this isn't a concrete subclass needing a STI type condition. - def descends_from_active_record? - if superclass.abstract_class? - superclass.descends_from_active_record? - else - superclass == Base || !columns_hash.include?(inheritance_column) - end - end - - def finder_needs_type_condition? #:nodoc: - # This is like this because benchmarking justifies the strange :false stuff - :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) - end - - # Returns a string like 'Post(id:integer, title:string, body:text)' - def inspect - if self == Base - super - elsif abstract_class? - "#{super}(abstract)" - elsif table_exists? - attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', ' - "#{super}(#{attr_list})" - else - "#{super}(Table doesn't exist)" - end - end - - def quote_value(value, column = nil) #:nodoc: - connection.quote(value,column) - end - - # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. - def sanitize(object) #:nodoc: - connection.quote(object) - end - - # Overwrite the default class equality method to provide support for association proxies. - def ===(object) - object.is_a?(self) - end - - def symbolized_base_class - @symbolized_base_class ||= base_class.to_s.to_sym - end - - def symbolized_sti_name - @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class - end - - # Returns the base AR subclass that this class descends from. If A - # extends AR::Base, A.base_class will return A. If B descends from A - # through some arbitrarily deep hierarchy, B.base_class will return A. - # - # If B < A and C < B and if A is an abstract_class then both B.base_class - # and C.base_class would return B as the answer since A is an abstract_class. - def base_class - class_of_active_record_descendant(self) - end - - # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). - attr_accessor :abstract_class - - # Returns whether this class is an abstract class or not. - def abstract_class? - defined?(@abstract_class) && @abstract_class == true - end - - def respond_to?(method_id, include_private = false) - if match = DynamicFinderMatch.match(method_id) - return true if all_attributes_exists?(match.attribute_names) - elsif match = DynamicScopeMatch.match(method_id) - return true if all_attributes_exists?(match.attribute_names) - end - - super - end - - def sti_name - store_full_sti_class ? name : name.demodulize - end - - def arel_table - @arel_table ||= Arel::Table.new(table_name, arel_engine) - end - - def arel_engine - @arel_engine ||= begin - if self == ActiveRecord::Base - ActiveRecord::Base - else - connection_handler.connection_pools[name] ? self : superclass.arel_engine - end - end - end - - # Returns a scope for this class without taking into account the default_scope. - # - # class Post < ActiveRecord::Base - # def self.default_scope - # where :published => true - # end - # end - # - # Post.all # Fires "SELECT * FROM posts WHERE published = true" - # Post.unscoped.all # Fires "SELECT * FROM posts" - # - # This method also accepts a block meaning that all queries inside the block will - # not use the default_scope: - # - # Post.unscoped { - # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10" - # } - # - # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt> - # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same. - # - # Post.unscoped.published - # Post.published - def unscoped #:nodoc: - block_given? ? relation.scoping { yield } : relation - end - - def before_remove_const #:nodoc: - self.current_scope = nil - end - - # Finder methods must instantiate through this method to work with the - # single-table inheritance model that makes it possible to create - # objects of different types from the same table. - def instantiate(record) - sti_class = find_sti_class(record[inheritance_column]) - record_id = sti_class.primary_key? && record[sti_class.primary_key] - - if ActiveRecord::IdentityMap.enabled? && record_id - if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number? - record_id = record_id.to_i - end - if instance = IdentityMap.get(sti_class, record_id) - instance.reinit_with('attributes' => record) - else - instance = sti_class.allocate.init_with('attributes' => record) - IdentityMap.add(instance) - end - else - instance = sti_class.allocate.init_with('attributes' => record) - end - - instance - end - - private - - def relation #:nodoc: - @relation ||= Relation.new(self, arel_table) - - if finder_needs_type_condition? - @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) - else - @relation - end - end - - def find_sti_class(type_name) - if type_name.blank? || !columns_hash.include?(inheritance_column) - self - else - begin - if store_full_sti_class - ActiveSupport::Dependencies.constantize(type_name) - else - compute_type(type_name) - end - rescue NameError - raise SubclassNotFound, - "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " + - "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + - "Please rename this column if you didn't intend it to be used for storing the inheritance class " + - "or overwrite #{name}.inheritance_column to use another column for that information." - end - end - end - - def construct_finder_arel(options = {}, scope = nil) - relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options - relation = scope.merge(relation) if scope - relation - end - - def type_condition(table = arel_table) - sti_column = table[inheritance_column.to_sym] - sti_names = ([self] + descendants).map { |model| model.sti_name } - - sti_column.in(sti_names) - end - - # Guesses the table name, but does not decorate it with prefix and suffix information. - def undecorated_table_name(class_name = base_class.name) - table_name = class_name.to_s.demodulize.underscore - table_name = table_name.pluralize if pluralize_table_names - table_name - end - - # Computes and returns a table name according to default conventions. - def compute_table_name - base = base_class - if self == base - # Nested classes are prefixed with singular parent table name. - if parent < ActiveRecord::Base && !parent.abstract_class? - contained = parent.table_name - contained = contained.singularize if parent.pluralize_table_names - contained += '_' - end - "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}" - else - # STI subclasses always use their superclass' table. - base.table_name - end - end - - # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and - # <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders - # section at the top of this file for more detailed information. - # - # It's even possible to use all the additional parameters to +find+. For example, the - # full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>. - # - # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it - # is first invoked, so that future attempts to use it do not run through method_missing. - def method_missing(method_id, *arguments, &block) - if match = (DynamicFinderMatch.match(method_id) || DynamicScopeMatch.match(method_id)) - attribute_names = match.attribute_names - super unless all_attributes_exists?(attribute_names) - if arguments.size < attribute_names.size - method_trace = "#{__FILE__}:#{__LINE__}:in `#{method_id}'" - backtrace = [method_trace] + caller - raise ArgumentError, "wrong number of arguments (#{arguments.size} for #{attribute_names.size})", backtrace - end - if match.respond_to?(:scope?) && match.scope? - self.class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args) - attributes = Hash[[:#{attribute_names.join(',:')}].zip(args)] # attributes = Hash[[:user_name, :password].zip(args)] - # - scoped(:conditions => attributes) # scoped(:conditions => attributes) - end # end - METHOD - send(method_id, *arguments) - elsif match.finder? - options = arguments.extract_options! - relation = options.any? ? scoped(options) : scoped - relation.send :find_by_attributes, match, attribute_names, *arguments, &block - elsif match.instantiator? - scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block - end - else - super - end - end - - # Similar in purpose to +expand_hash_conditions_for_aggregates+. - def expand_attribute_names_for_aggregates(attribute_names) - attribute_names.map { |attribute_name| - unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? - aggregate_mapping(aggregation).map do |field_attr, _| - field_attr.to_sym - end - else - attribute_name.to_sym - end - }.flatten - end - - def all_attributes_exists?(attribute_names) - (expand_attribute_names_for_aggregates(attribute_names) - - column_methods_hash.keys).empty? - end - - protected - # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be - # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while - # <tt>:create</tt> parameters are an attributes hash. - # - # class Article < ActiveRecord::Base - # def self.create_with_scope - # with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do - # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 - # a = create(1) - # a.blog_id # => 1 - # end - # end - # end - # - # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of - # <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged. - # - # <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing - # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the - # array of strings format for your joins. - # - # class Article < ActiveRecord::Base - # def self.find_with_scope - # with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do - # with_scope(:find => limit(10)) do - # all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 - # end - # with_scope(:find => where(:author_id => 3)) do - # all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 - # end - # end - # end - # end - # - # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method. - # - # class Article < ActiveRecord::Base - # def self.find_with_exclusive_scope - # with_scope(:find => where(:blog_id => 1).limit(1)) do - # with_exclusive_scope(:find => limit(10)) do - # all # => SELECT * from articles LIMIT 10 - # end - # end - # end - # end - # - # *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+. - def with_scope(scope = {}, action = :merge, &block) - # If another Active Record class has been passed in, get its current scope - scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope) - - previous_scope = self.current_scope - - if scope.is_a?(Hash) - # Dup first and second level of hash (method and params). - scope = scope.dup - scope.each do |method, params| - scope[method] = params.dup unless params == true - end - - scope.assert_valid_keys([ :find, :create ]) - relation = construct_finder_arel(scope[:find] || {}) - relation.default_scoped = true unless action == :overwrite - - if previous_scope && previous_scope.create_with_value && scope[:create] - scope_for_create = if action == :merge - previous_scope.create_with_value.merge(scope[:create]) - else - scope[:create] - end - - relation = relation.create_with(scope_for_create) - else - scope_for_create = scope[:create] - scope_for_create ||= previous_scope.create_with_value if previous_scope - relation = relation.create_with(scope_for_create) if scope_for_create - end - - scope = relation - end - - scope = previous_scope.merge(scope) if previous_scope && action == :merge - - self.current_scope = scope - begin - yield - ensure - self.current_scope = previous_scope - end - end - - # Works like with_scope, but discards any nested properties. - def with_exclusive_scope(method_scoping = {}, &block) - if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } - raise ArgumentError, <<-MSG -New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: - - User.unscoped.where(:active => true) - -Or call unscoped with a block: - - User.unscoped do - User.where(:active => true).all - end - -MSG - end - with_scope(method_scoping, :overwrite, &block) - end - - def current_scope #:nodoc: - Thread.current["#{self}_current_scope"] - end - - def current_scope=(scope) #:nodoc: - Thread.current["#{self}_current_scope"] = scope - end - - # Use this macro in your model to set a default scope for all operations on - # the model. - # - # class Article < ActiveRecord::Base - # default_scope where(:published => true) - # end - # - # Article.all # => SELECT * FROM articles WHERE published = true - # - # The <tt>default_scope</tt> is also applied while creating/building a record. It is not - # applied while updating a record. - # - # Article.new.published # => true - # Article.create.published # => true - # - # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated: - # - # class Article < ActiveRecord::Base - # default_scope { where(:published_at => Time.now - 1.week) } - # end - # - # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt> - # macro, and it will be called when building the default scope.) - # - # If you use multiple <tt>default_scope</tt> declarations in your model then they will - # be merged together: - # - # class Article < ActiveRecord::Base - # default_scope where(:published => true) - # default_scope where(:rating => 'G') - # end - # - # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G' - # - # This is also the case with inheritance and module includes where the parent or module - # defines a <tt>default_scope</tt> and the child or including class defines a second one. - # - # If you need to do more complex things with a default scope, you can alternatively - # define it as a class method: - # - # class Article < ActiveRecord::Base - # def self.default_scope - # # Should return a scope, you can call 'super' here etc. - # end - # end - def default_scope(scope = {}) - scope = Proc.new if block_given? - self.default_scopes = default_scopes + [scope] - end - - def build_default_scope #:nodoc: - if method(:default_scope).owner != Base.singleton_class - evaluate_default_scope { default_scope } - elsif default_scopes.any? - evaluate_default_scope do - default_scopes.inject(relation) do |default_scope, scope| - if scope.is_a?(Hash) - default_scope.apply_finder_options(scope) - elsif !scope.is_a?(Relation) && scope.respond_to?(:call) - default_scope.merge(scope.call) - else - default_scope.merge(scope) - end - end - end - end - end - - def ignore_default_scope? #:nodoc: - Thread.current["#{self}_ignore_default_scope"] - end - - def ignore_default_scope=(ignore) #:nodoc: - Thread.current["#{self}_ignore_default_scope"] = ignore - end - - # The ignore_default_scope flag is used to prevent an infinite recursion situation where - # a default scope references a scope which has a default scope which references a scope... - def evaluate_default_scope - return if ignore_default_scope? - - begin - self.ignore_default_scope = true - yield - ensure - self.ignore_default_scope = false - end - end - - # Returns the class type of the record using the current module as a prefix. So descendants of - # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. - def compute_type(type_name) - if type_name.match(/^::/) - # If the type is prefixed with a scope operator then we assume that - # the type_name is an absolute reference. - ActiveSupport::Dependencies.constantize(type_name) - else - # Build a list of candidates to search for - candidates = [] - name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } - candidates << type_name - - candidates.each do |candidate| - begin - constant = ActiveSupport::Dependencies.constantize(candidate) - return constant if candidate == constant.to_s - rescue NameError => e - # We don't want to swallow NoMethodError < NameError errors - raise e unless e.instance_of?(NameError) - end - end - - raise NameError, "uninitialized constant #{candidates.first}" - end - end - - # Returns the class descending directly from ActiveRecord::Base or an - # abstract class, if any, in the inheritance hierarchy. - def class_of_active_record_descendant(klass) - if klass == Base || klass.superclass == Base || klass.superclass.abstract_class? - klass - elsif klass.superclass.nil? - raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" - else - class_of_active_record_descendant(klass.superclass) - end - end - - # Accepts an array, hash, or string of SQL conditions and sanitizes - # them into a valid SQL fragment for a WHERE clause. - # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" - # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" - # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'" - def sanitize_sql_for_conditions(condition, table_name = self.table_name) - return nil if condition.blank? - - case condition - when Array; sanitize_sql_array(condition) - when Hash; sanitize_sql_hash_for_conditions(condition, table_name) - else condition - end - end - alias_method :sanitize_sql, :sanitize_sql_for_conditions - - # Accepts an array, hash, or string of SQL conditions and sanitizes - # them into a valid SQL fragment for a SET clause. - # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'" - def sanitize_sql_for_assignment(assignments) - case assignments - when Array; sanitize_sql_array(assignments) - when Hash; sanitize_sql_hash_for_assignment(assignments) - else assignments - end - end - - def aggregate_mapping(reflection) - mapping = reflection.options[:mapping] || [reflection.name, reflection.name] - mapping.first.is_a?(Array) ? mapping : [mapping] - end - - # Accepts a hash of SQL conditions and replaces those attributes - # that correspond to a +composed_of+ relationship with their expanded - # aggregate attribute values. - # Given: - # class Person < ActiveRecord::Base - # composed_of :address, :class_name => "Address", - # :mapping => [%w(address_street street), %w(address_city city)] - # end - # Then: - # { :address => Address.new("813 abc st.", "chicago") } - # # => { :address_street => "813 abc st.", :address_city => "chicago" } - def expand_hash_conditions_for_aggregates(attrs) - expanded_attrs = {} - attrs.each do |attr, value| - unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil? - mapping = aggregate_mapping(aggregation) - mapping.each do |field_attr, aggregate_attr| - if mapping.size == 1 && !value.respond_to?(aggregate_attr) - expanded_attrs[field_attr] = value - else - expanded_attrs[field_attr] = value.send(aggregate_attr) - end - end - else - expanded_attrs[attr] = value - end - end - expanded_attrs - end - - # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause. - # { :name => "foo'bar", :group_id => 4 } - # # => "name='foo''bar' and group_id= 4" - # { :status => nil, :group_id => [1,2,3] } - # # => "status IS NULL and group_id IN (1,2,3)" - # { :age => 13..18 } - # # => "age BETWEEN 13 AND 18" - # { 'other_records.id' => 7 } - # # => "`other_records`.`id` = 7" - # { :other_records => { :id => 7 } } - # # => "`other_records`.`id` = 7" - # 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'" - def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) - attrs = expand_hash_conditions_for_aggregates(attrs) - - table = Arel::Table.new(table_name).alias(default_table_name) - PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b| - connection.visitor.accept b - }.join(' AND ') - end - alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions - - # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. - # { :status => nil, :group_id => 1 } - # # => "status = NULL , group_id = 1" - def sanitize_sql_hash_for_assignment(attrs) - attrs.map do |attr, value| - "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}" - end.join(', ') - end - - # Accepts an array of conditions. The array has each value - # sanitized and interpolated into the SQL statement. - # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" - def sanitize_sql_array(ary) - statement, *values = ary - if values.first.is_a?(Hash) && statement =~ /:\w+/ - replace_named_bind_variables(statement, values.first) - elsif statement.include?('?') - replace_bind_variables(statement, values) - elsif statement.blank? - statement - else - statement % values.collect { |value| connection.quote_string(value.to_s) } - end - end - - alias_method :sanitize_conditions, :sanitize_sql - - def replace_bind_variables(statement, values) #:nodoc: - raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) - bound = values.dup - c = connection - statement.gsub('?') { quote_bound_value(bound.shift, c) } - end - - def replace_named_bind_variables(statement, bind_vars) #:nodoc: - statement.gsub(/(:?):([a-zA-Z]\w*)/) do - if $1 == ':' # skip postgresql casts - $& # return the whole match - elsif bind_vars.include?(match = $2.to_sym) - quote_bound_value(bind_vars[match]) - else - raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" - end - end - end - - def expand_range_bind_variables(bind_vars) #:nodoc: - expanded = [] - - bind_vars.each do |var| - next if var.is_a?(Hash) - - if var.is_a?(Range) - expanded << var.first - expanded << var.last - else - expanded << var - end - end - - expanded - end - - def quote_bound_value(value, c = connection) #:nodoc: - if value.respond_to?(:map) && !value.acts_like?(:string) - if value.respond_to?(:empty?) && value.empty? - c.quote(nil) - else - value.map { |v| c.quote(v) }.join(',') - end - else - c.quote(value) - end - end - - def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc: - unless expected == provided - raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" - end - end - - def encode_quoted_value(value) #:nodoc: - quoted_value = connection.quote(value) - quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'") # (for ruby mode) " - quoted_value - end - end - - public - # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with - # attributes but not yet saved (pass a hash with key names matching the associated table column names). - # In both instances, valid attribute keys are determined by the column names of the associated table -- - # hence you can't have attributes that aren't part of the table columns. - # - # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options - # in the +options+ parameter. - # - # ==== Examples - # # Instantiates a single new object - # User.new(:first_name => 'Jamie') - # - # # Instantiates a single new object using the :admin mass-assignment security role - # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) - # - # # Instantiates a single new object bypassing mass-assignment security - # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) - def initialize(attributes = nil, options = {}) - @attributes = attributes_from_column_definition - @association_cache = {} - @aggregation_cache = {} - @attributes_cache = {} - @new_record = true - @readonly = false - @destroyed = false - @marked_for_destruction = false - @previously_changed = {} - @changed_attributes = {} - @relation = nil - - ensure_proper_type - set_serialized_attributes - - populate_with_current_scope_attributes - - assign_attributes(attributes, options) if attributes - - yield self if block_given? - run_callbacks :initialize - end - - # Populate +coder+ with attributes about this record that should be - # serialized. The structure of +coder+ defined in this method is - # guaranteed to match the structure of +coder+ passed to the +init_with+ - # method. - # - # Example: - # - # class Post < ActiveRecord::Base - # end - # coder = {} - # Post.new.encode_with(coder) - # coder # => { 'id' => nil, ... } - def encode_with(coder) - coder['attributes'] = attributes - end - - # Initialize an empty model object from +coder+. +coder+ must contain - # the attributes necessary for initializing an empty model object. For - # example: - # - # class Post < ActiveRecord::Base - # end - # - # post = Post.allocate - # post.init_with('attributes' => { 'title' => 'hello world' }) - # post.title # => 'hello world' - def init_with(coder) - @attributes = coder['attributes'] - @relation = nil - - set_serialized_attributes - - @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {} - @association_cache = {} - @aggregation_cache = {} - @readonly = @destroyed = @marked_for_destruction = false - @new_record = false - run_callbacks :find - run_callbacks :initialize - - self - end - - # Returns a String, which Action Pack uses for constructing an URL to this - # object. The default implementation returns this record's id as a String, - # or nil if this record's unsaved. - # - # For example, suppose that you have a User model, and that you have a - # <tt>resources :users</tt> route. Normally, +user_path+ will - # construct a path with the user object's 'id' in it: - # - # user = User.find_by_name('Phusion') - # user_path(user) # => "/users/1" - # - # You can override +to_param+ in your model to make +user_path+ construct - # a path using the user's name instead of the user's id: - # - # class User < ActiveRecord::Base - # def to_param # overridden - # name - # end - # end - # - # user = User.find_by_name('Phusion') - # user_path(user) # => "/users/Phusion" - def to_param - # We can't use alias_method here, because method 'id' optimizes itself on the fly. - id && id.to_s # Be sure to stringify the id for routes - end - - # Returns a cache key that can be used to identify this record. - # - # ==== Examples - # - # Product.new.cache_key # => "products/new" - # Product.find(5).cache_key # => "products/5" (updated_at not available) - # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available) - def cache_key - case - when new_record? - "#{self.class.model_name.cache_key}/new" - when timestamp = self[:updated_at] - timestamp = timestamp.utc.to_s(:number) - "#{self.class.model_name.cache_key}/#{id}-#{timestamp}" - else - "#{self.class.model_name.cache_key}/#{id}" - end - end - - def quoted_id #:nodoc: - quote_value(id, column_for_attribute(self.class.primary_key)) - end - - # Returns true if the given attribute is in the attributes hash - def has_attribute?(attr_name) - @attributes.has_key?(attr_name.to_s) - end - - # Returns an array of names for the attributes available on this object. - def attribute_names - @attributes.keys - end - - # Allows you to set all the attributes at once by passing in a hash with keys - # matching the attribute names (which again matches the column names). - # - # If any attributes are protected by either +attr_protected+ or - # +attr_accessible+ then only settable attributes will be assigned. - # - # class User < ActiveRecord::Base - # attr_protected :is_admin - # end - # - # user = User.new - # user.attributes = { :username => 'Phusion', :is_admin => true } - # user.username # => "Phusion" - # user.is_admin? # => false - def attributes=(new_attributes) - return unless new_attributes.is_a?(Hash) - - assign_attributes(new_attributes) - end - - # Allows you to set all the attributes for a particular mass-assignment - # security role by passing in a hash of attributes with keys matching - # the attribute names (which again matches the column names) and the role - # name using the :as option. - # - # To bypass mass-assignment security you can use the :without_protection => true - # option. - # - # class User < ActiveRecord::Base - # attr_accessible :name - # attr_accessible :name, :is_admin, :as => :admin - # end - # - # user = User.new - # user.assign_attributes({ :name => 'Josh', :is_admin => true }) - # user.name # => "Josh" - # user.is_admin? # => false - # - # user = User.new - # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin) - # user.name # => "Josh" - # user.is_admin? # => true - # - # user = User.new - # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true) - # user.name # => "Josh" - # user.is_admin? # => true - def assign_attributes(new_attributes, options = {}) - return unless new_attributes - - attributes = new_attributes.stringify_keys - multi_parameter_attributes = [] - @mass_assignment_options = options - - unless options[:without_protection] - attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role) - end - - attributes.each do |k, v| - if k.include?("(") - multi_parameter_attributes << [ k, v ] - elsif respond_to?("#{k}=") - send("#{k}=", v) - else - raise(UnknownAttributeError, "unknown attribute: #{k}") - end - end - - @mass_assignment_options = nil - assign_multiparameter_attributes(multi_parameter_attributes) - end - - # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. - def attributes - Hash[@attributes.map { |name, _| [name, read_attribute(name)] }] - end - - # Returns an <tt>#inspect</tt>-like string for the value of the - # attribute +attr_name+. String attributes are truncated upto 50 - # characters, and Date and Time attributes are returned in the - # <tt>:db</tt> format. Other attributes return the value of - # <tt>#inspect</tt> without modification. - # - # person = Person.create!(:name => "David Heinemeier Hansson " * 3) - # - # person.attribute_for_inspect(:name) - # # => '"David Heinemeier Hansson David Heinemeier Hansson D..."' - # - # person.attribute_for_inspect(:created_at) - # # => '"2009-01-12 04:48:57"' - def attribute_for_inspect(attr_name) - value = read_attribute(attr_name) - - if value.is_a?(String) && value.length > 50 - "#{value[0..50]}...".inspect - elsif value.is_a?(Date) || value.is_a?(Time) - %("#{value.to_s(:db)}") - else - value.inspect - end - end - - # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither - # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings). - def attribute_present?(attribute) - !_read_attribute(attribute).blank? - end - - # Returns the column object for the named attribute. - def column_for_attribute(name) - self.class.columns_hash[name.to_s] - end - - # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ - # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+. - # - # Note that new records are different from any other record by definition, unless the - # other record is the receiver itself. Besides, if you fetch existing records with - # +select+ and leave the ID out, you're on your own, this predicate will return false. - # - # Note also that destroying a record preserves its ID in the model instance, so deleted - # models are still comparable. - def ==(comparison_object) - super || - comparison_object.instance_of?(self.class) && - id.present? && - comparison_object.id == id - end - alias :eql? :== - - # Delegates to id in order to allow two records of the same type and id to work with something like: - # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] - def hash - id.hash - end - - # Freeze the attributes hash such that associations are still accessible, even on destroyed records. - def freeze - @attributes.freeze; self - end - - # Returns +true+ if the attributes hash has been frozen. - def frozen? - @attributes.frozen? - end - - # Allows sort on objects - def <=>(other_object) - if other_object.is_a?(self.class) - self.to_key <=> other_object.to_key - else - nil - end - end - - # Backport dup from 1.9 so that initialize_dup() gets called - unless Object.respond_to?(:initialize_dup) - def dup # :nodoc: - copy = super - copy.initialize_dup(self) - copy - end - end - - # Duped objects have no id assigned and are treated as new records. Note - # that this is a "shallow" copy as it copies the object's attributes - # only, not its associations. The extent of a "deep" copy is application - # specific and is therefore left to the application to implement according - # to its need. - # The dup method does not preserve the timestamps (created|updated)_(at|on). - def initialize_dup(other) - cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast) - cloned_attributes.delete(self.class.primary_key) - - @attributes = cloned_attributes - - _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks) - - @changed_attributes = {} - attributes_from_column_definition.each do |attr, orig_value| - @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr]) - end - - @aggregation_cache = {} - @association_cache = {} - @attributes_cache = {} - @new_record = true - - ensure_proper_type - populate_with_current_scope_attributes - super - end - - # Returns +true+ if the record is read only. Records loaded through joins with piggy-back - # attributes will be marked as read only since they cannot be saved. - def readonly? - @readonly - end - - # Marks this record as read only. - def readonly! - @readonly = true - end - - # Returns the contents of the record as a nicely formatted string. - def inspect - inspection = if @attributes - self.class.column_names.collect { |name| - if has_attribute?(name) - "#{name}: #{attribute_for_inspect(name)}" - end - }.compact.join(", ") - else - "not initialized" - end - "#<#{self.class} #{inspection}>" - end - - protected - def clone_attributes(reader_method = :read_attribute, attributes = {}) - attribute_names.each do |name| - attributes[name] = clone_attribute_value(reader_method, name) - end - attributes - end - - def clone_attribute_value(reader_method, attribute_name) - value = send(reader_method, attribute_name) - value.duplicable? ? value.clone : value - rescue TypeError, NoMethodError - value - end - - def mass_assignment_options - @mass_assignment_options ||= {} - end - - def mass_assignment_role - mass_assignment_options[:as] || :default - end - - private - - # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements - # of the array, and then rescues from the possible NoMethodError. If those elements are - # ActiveRecord::Base's, then this triggers the various method_missing's that we have, - # which significantly impacts upon performance. - # - # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here. - # - # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/ - def to_ary # :nodoc: - nil - end - - def set_serialized_attributes - sattrs = self.class.serialized_attributes - - sattrs.each do |key, coder| - @attributes[key] = coder.load @attributes[key] if @attributes.key?(key) - end - end - - # Sets the attribute used for single table inheritance to this class name if this is not the - # ActiveRecord::Base descendant. - # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to - # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. - # No such attribute would be set for objects of the Message class in that example. - def ensure_proper_type - klass = self.class - if klass.finder_needs_type_condition? - write_attribute(klass.inheritance_column, klass.sti_name) - end - end - - # The primary key and inheritance column can never be set by mass-assignment for security reasons. - def self.attributes_protected_by_default - default = [ inheritance_column ] - default << primary_key if primary_key? - default << 'id' unless primary_key? && primary_key == 'id' - default - end - - # Returns a copy of the attributes hash where all the values have been safely quoted for use in - # an Arel insert/update method. - def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys) - attrs = {} - klass = self.class - arel_table = klass.arel_table - - attribute_names.each do |name| - if (column = column_for_attribute(name)) && (include_primary_key || !column.primary) - - if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name)) - - value = if coder = klass.serialized_attributes[name] - coder.dump @attributes[name] - else - # FIXME: we need @attributes to be used consistently. - # If the values stored in @attributes were already type - # casted, this code could be simplified - read_attribute(name) - end - - attrs[arel_table[name]] = value - end - end - end - attrs - end - - # Quote strings appropriately for SQL statements. - def quote_value(value, column = nil) - self.class.connection.quote(value, column) - end - - # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done - # by calling new on the column type or aggregation type (through composed_of) object with these parameters. - # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate - # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the - # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, - # f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the - # attribute will be set to nil. - def assign_multiparameter_attributes(pairs) - execute_callstack_for_multiparameter_attributes( - extract_callstack_for_multiparameter_attributes(pairs) - ) - end - - def instantiate_time_object(name, values) - if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name)) - Time.zone.local(*values) - else - Time.time_with_datetime_fallback(@@default_timezone, *values) - end - end - - def execute_callstack_for_multiparameter_attributes(callstack) - errors = [] - callstack.each do |name, values_with_empty_parameters| - begin - send(name + "=", read_value_from_parameter(name, values_with_empty_parameters)) - rescue => ex - errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name}", ex, name) - end - end - unless errors.empty? - raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes" - end - end - - def read_value_from_parameter(name, values_hash_from_param) - klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass - if values_hash_from_param.values.all?{|v|v.nil?} - nil - elsif klass == Time - read_time_parameter_value(name, values_hash_from_param) - elsif klass == Date - read_date_parameter_value(name, values_hash_from_param) - else - read_other_parameter_value(klass, name, values_hash_from_param) - end - end - - def read_time_parameter_value(name, values_hash_from_param) - # If Date bits were not provided, error - raise "Missing Parameter" if [1,2,3].any?{|position| !values_hash_from_param.has_key?(position)} - max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param, 6) - # If Date bits were provided but blank, then return nil - return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} - - set_values = (1..max_position).collect{|position| values_hash_from_param[position] } - # If Time bits are not there, then default to 0 - (3..5).each {|i| set_values[i] = set_values[i].blank? ? 0 : set_values[i]} - instantiate_time_object(name, set_values) - end - - def read_date_parameter_value(name, values_hash_from_param) - return nil if (1..3).any? {|position| values_hash_from_param[position].blank?} - set_values = [values_hash_from_param[1], values_hash_from_param[2], values_hash_from_param[3]] - begin - Date.new(*set_values) - rescue ArgumentError # if Date.new raises an exception on an invalid date - instantiate_time_object(name, set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates - end - end - - def read_other_parameter_value(klass, name, values_hash_from_param) - max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param) - values = (1..max_position).collect do |position| - raise "Missing Parameter" if !values_hash_from_param.has_key?(position) - values_hash_from_param[position] - end - klass.new(*values) - end - - def extract_max_param_for_multiparameter_attributes(values_hash_from_param, upper_cap = 100) - [values_hash_from_param.keys.max,upper_cap].min - end - - def extract_callstack_for_multiparameter_attributes(pairs) - attributes = { } - - pairs.each do |pair| - multiparameter_name, value = pair - attribute_name = multiparameter_name.split("(").first - attributes[attribute_name] = {} unless attributes.include?(attribute_name) - - parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) - attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value - end - - attributes - end - - def type_cast_attribute_value(multiparameter_name, value) - multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value - end - - def find_parameter_position(multiparameter_name) - multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i - end - - # Returns a comma-separated pair list, like "key1 = val1, key2 = val2". - def comma_pair_list(hash) - hash.map { |k,v| "#{k} = #{v}" }.join(", ") - end - - def quote_columns(quoter, hash) - Hash[hash.map { |name, value| [quoter.quote_column_name(name), value] }] - end - - def quoted_comma_pair_list(quoter, hash) - comma_pair_list(quote_columns(quoter, hash)) - end - - def convert_number_column_value(value) - if value == false - 0 - elsif value == true - 1 - elsif value.is_a?(String) && value.blank? - nil - else - value - end - end - - def populate_with_current_scope_attributes - return unless self.class.scope_attributes? - - self.class.scope_attributes.each do |att,value| - send("#{att}=", value) if respond_to?("#{att}=") - end - end - end - - Base.class_eval do - include ActiveRecord::Persistence - extend ActiveModel::Naming - extend QueryCache::ClassMethods - extend ActiveSupport::Benchmarkable - extend ActiveSupport::DescendantsTracker - - include ActiveModel::Conversion - include Validations - extend CounterCache - include Locking::Optimistic, Locking::Pessimistic - include AttributeMethods - include AttributeMethods::Read, AttributeMethods::Write, AttributeMethods::BeforeTypeCast, AttributeMethods::Query - include AttributeMethods::PrimaryKey - include AttributeMethods::TimeZoneConversion - include AttributeMethods::Dirty - include ActiveModel::MassAssignmentSecurity - include Callbacks, ActiveModel::Observing, Timestamp - include Associations, NamedScope - include IdentityMap - include ActiveModel::SecurePassword - - # AutosaveAssociation needs to be included before Transactions, because we want - # #save_with_autosave_associations to be wrapped inside a transaction. - include AutosaveAssociation, NestedAttributes - include Aggregations, Transactions, Reflection, Serialization - - NilClass.add_whiner(self) if NilClass.respond_to?(:add_whiner) - - # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, - # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). - # (Alias for the protected read_attribute method). - alias [] read_attribute - - # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. - # (Alias for the protected write_attribute method). - alias []= write_attribute - - public :[], :[]= + include ActiveRecord::Model end end -require 'active_record/connection_adapters/abstract/connection_specification' -ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) +ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Model::DeprecationProxy) diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index a175bf003c..8b2fc69b00 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -25,7 +25,7 @@ module ActiveRecord # Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and # <tt>after_rollback</tt>. # - # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that + # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that # is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects # are instantiated as well. # @@ -215,24 +215,48 @@ module ActiveRecord # instead of quietly returning +false+. # # == Debugging callbacks - # - # The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support + # + # The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support # <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property # defines what part of the chain the callback runs in. - # - # To find all callbacks in the before_save callback chain: - # + # + # To find all callbacks in the before_save callback chain: + # # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) } - # + # # Returns an array of callback objects that form the before_save chain. - # + # # To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object: - # + # # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead) - # + # # Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model. - # + # module Callbacks + # We can't define callbacks directly on ActiveRecord::Model because + # it is a module. So we queue up the definitions and execute them + # when ActiveRecord::Model is included. + module Register #:nodoc: + def self.extended(base) + base.config_attribute :_callbacks_register + base._callbacks_register = [] + end + + def self.setup(base) + base._callbacks_register.each do |item| + base.send(*item) + end + end + + def define_callbacks(*args) + self._callbacks_register << [:define_callbacks, *args] + end + + def define_model_callbacks(*args) + self._callbacks_register << [:define_model_callbacks, *args] + end + end + extend ActiveSupport::Concern CALLBACKS = [ @@ -242,8 +266,11 @@ module ActiveRecord :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback ] + module ClassMethods + include ActiveModel::Callbacks + end + included do - extend ActiveModel::Callbacks include ActiveModel::Validations::Callbacks define_model_callbacks :initialize, :find, :touch, :only => :after diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 20863e73aa..b8f99adc22 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -1,7 +1,7 @@ require 'thread' require 'monitor' require 'set' -require 'active_support/core_ext/module/synchronization' +require 'active_support/core_ext/module/deprecation' module ActiveRecord # Raised when a connection could not be obtained within the connection @@ -9,6 +9,13 @@ module ActiveRecord class ConnectionTimeoutError < ConnectionNotEstablished end + # Raised when a connection pool is full and another connection is requested + class PoolFullError < ConnectionNotEstablished + def initialize size, timeout + super("Connection pool of size #{size} and timeout #{timeout}s is full") + end + end + module ConnectionAdapters # Connection pool base class for managing Active Record database # connections. @@ -57,10 +64,35 @@ module ActiveRecord # * +wait_timeout+: number of seconds to block and wait for a connection # before giving up and raising a timeout error (default 5 seconds). class ConnectionPool - attr_accessor :automatic_reconnect - attr_reader :spec, :connections - attr_reader :columns, :columns_hash, :primary_keys, :tables - attr_reader :column_defaults + # Every +frequency+ seconds, the reaper will call +reap+ on +pool+. + # A reaper instantiated with a nil frequency will never reap the + # connection pool. + # + # Configure the frequency by setting "reaping_frequency" in your + # database yaml file. + class Reaper + attr_reader :pool, :frequency + + def initialize(pool, frequency) + @pool = pool + @frequency = frequency + end + + def run + return unless frequency + Thread.new(frequency, pool) { |t, p| + while true + sleep t + p.reap + end + } + end + end + + include MonitorMixin + + attr_accessor :automatic_reconnect, :timeout + attr_reader :spec, :connections, :size, :reaper # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification # object which describes database connection information (e.g. adapter, @@ -69,88 +101,22 @@ module ActiveRecord # # The default ConnectionPool maximum size is 5. def initialize(spec) + super() + @spec = spec # The cache of reserved connections mapped to threads @reserved_connections = {} - # The mutex used to synchronize pool access - @connection_mutex = Monitor.new - @queue = @connection_mutex.new_cond @timeout = spec.config[:wait_timeout] || 5 + @reaper = Reaper.new self, spec.config[:reaping_frequency] + @reaper.run # default max pool size to 5 @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 @connections = [] - @checked_out = [] @automatic_reconnect = true - @tables = {} - @visitor = nil - - @columns = Hash.new do |h, table_name| - h[table_name] = with_connection do |conn| - - # Fetch a list of columns - conn.columns(table_name, "#{table_name} Columns").tap do |columns| - - # set primary key information - columns.each do |column| - column.primary = column.name == primary_keys[table_name] - end - end - end - end - - @columns_hash = Hash.new do |h, table_name| - h[table_name] = Hash[columns[table_name].map { |col| - [col.name, col] - }] - end - - @column_defaults = Hash.new do |h, table_name| - h[table_name] = Hash[columns[table_name].map { |col| - [col.name, col.default] - }] - end - - @primary_keys = Hash.new do |h, table_name| - h[table_name] = with_connection do |conn| - table_exists?(table_name) ? conn.primary_key(table_name) : 'id' - end - end - end - - # A cached lookup for table existence. - def table_exists?(name) - return true if @tables.key? name - - with_connection do |conn| - conn.tables.each { |table| @tables[table] = true } - @tables[name] = true if !@tables.key?(name) && conn.table_exists?(name) - end - - @tables.key? name - end - - # Clears out internal caches: - # - # * columns - # * columns_hash - # * tables - def clear_cache! - @columns.clear - @columns_hash.clear - @column_defaults.clear - @tables.clear - end - - # Clear out internal caches for table with +table_name+. - def clear_table_cache!(table_name) - @columns.delete table_name - @columns_hash.delete table_name - @column_defaults.delete table_name - @primary_keys.delete table_name end # Retrieve the connection associated with the current thread, or call @@ -165,7 +131,7 @@ module ActiveRecord # Check to see if there is an active connection in this connection # pool. def active_connection? - @reserved_connections.key? current_connection_id + active_connections.any? end # Signal that the thread is finished with the current connection. @@ -181,7 +147,7 @@ module ActiveRecord # connection when finished. def with_connection connection_id = current_connection_id - fresh_connection = true unless @reserved_connections[connection_id] + fresh_connection = true unless active_connection? yield connection ensure release_connection(connection_id) if fresh_connection @@ -189,94 +155,80 @@ module ActiveRecord # Returns true if a connection has already been opened. def connected? - !@connections.empty? + synchronize { @connections.any? } end # Disconnects all connections in the pool, and clears the pool. def disconnect! - @reserved_connections.each do |name,conn| - checkin conn - end - @reserved_connections = {} - @connections.each do |conn| - conn.disconnect! + synchronize do + @reserved_connections = {} + @connections.each do |conn| + checkin conn + conn.disconnect! + end + @connections = [] end - @connections = [] end # Clears the cache which maps classes. def clear_reloadable_connections! - @reserved_connections.each do |name, conn| - checkin conn - end - @reserved_connections = {} - @connections.each do |conn| - conn.disconnect! if conn.requires_reloading? - end - @connections.delete_if do |conn| - conn.requires_reloading? + synchronize do + @reserved_connections = {} + @connections.each do |conn| + checkin conn + conn.disconnect! if conn.requires_reloading? + end + @connections.delete_if do |conn| + conn.requires_reloading? + end end end # Verify active connections and remove and disconnect connections # associated with stale threads. def verify_active_connections! #:nodoc: - clear_stale_cached_connections! - @connections.each do |connection| - connection.verify! + synchronize do + @connections.each do |connection| + connection.verify! + end end end - # Return any checked-out connections back to the pool by threads that - # are no longer alive. - def clear_stale_cached_connections! - keys = @reserved_connections.keys - Thread.list.find_all { |t| - t.alive? - }.map { |thread| thread.object_id } - keys.each do |key| - checkin @reserved_connections[key] - @reserved_connections.delete(key) - end + def clear_stale_cached_connections! # :nodoc: end + deprecate :clear_stale_cached_connections! # Check-out a database connection from the pool, indicating that you want # to use it. You should call #checkin when you no longer need this. # - # This is done by either returning an existing connection, or by creating - # a new connection. If the maximum number of connections for this pool has - # already been reached, but the pool is empty (i.e. they're all being used), - # then this method will wait until a thread has checked in a connection. - # The wait time is bounded however: if no connection can be checked out - # within the timeout specified for this pool, then a ConnectionTimeoutError - # exception will be raised. + # This is done by either returning and leasing existing connection, or by + # creating a new connection and leasing it. + # + # If all connections are leased and the pool is at capacity (meaning the + # number of currently leased connections is greater than or equal to the + # size limit set), an ActiveRecord::PoolFullError exception will be raised. # # Returns: an AbstractAdapter object. # # Raises: - # - ConnectionTimeoutError: no connection can be obtained from the pool - # within the timeout period. + # - PoolFullError: no connection can be obtained from the pool. def checkout # Checkout an available connection - @connection_mutex.synchronize do - loop do - conn = if @checked_out.size < @connections.size - checkout_existing_connection - elsif @connections.size < @size - checkout_new_connection - end - return conn if conn - - @queue.wait(@timeout) - - if(@checked_out.size < @connections.size) - next - else - clear_stale_cached_connections! - if @size == @checked_out.size - raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it." - end - end + synchronize do + # Try to find a connection that hasn't been leased, and lease it + conn = connections.find { |c| c.lease } + + # If all connections were leased, and we have room to expand, + # create a new connection and lease it. + if !conn && connections.size < size + conn = checkout_new_connection + conn.lease + end + if conn + checkout_and_verify conn + else + raise PoolFullError.new(size, timeout) end end end @@ -287,56 +239,69 @@ module ActiveRecord # +conn+: an AbstractAdapter object, which was obtained by earlier by # calling +checkout+ on this pool. def checkin(conn) - @connection_mutex.synchronize do + synchronize do conn.run_callbacks :checkin do - @checked_out.delete conn - @queue.signal + conn.expire end end end - synchronize :clear_reloadable_connections!, :verify_active_connections!, - :connected?, :disconnect!, :with => :@connection_mutex + # Remove a connection from the connection pool. The connection will + # remain open and active but will no longer be managed by this pool. + def remove(conn) + synchronize do + @connections.delete conn - private + # FIXME: we might want to store the key on the connection so that removing + # from the reserved hash will be a little easier. + thread_id = @reserved_connections.keys.find { |k| + @reserved_connections[k] == conn + } + @reserved_connections.delete thread_id if thread_id + end + end - def new_connection - connection = ActiveRecord::Base.send(spec.adapter_method, spec.config) + # Removes dead connections from the pool. A dead connection can occur + # if a programmer forgets to close a connection at the end of a thread + # or a thread dies unexpectedly. + def reap + synchronize do + stale = Time.now - @timeout + connections.dup.each do |conn| + remove conn if conn.in_use? && stale > conn.last_use && !conn.active? + end + end + end - # TODO: This is a bit icky, and in the long term we may want to change the method - # signature for connections. Also, if we switch to have one visitor per - # connection (and therefore per thread), we can get rid of the thread-local - # variable in Arel::Visitors::ToSql. - @visitor ||= connection.class.visitor_for(self) - connection.visitor = @visitor + private - connection + def new_connection + ActiveRecord::Base.send(spec.adapter_method, spec.config) end def current_connection_id #:nodoc: - Thread.current.object_id + ActiveRecord::Base.connection_id ||= Thread.current.object_id end def checkout_new_connection raise ConnectionNotEstablished unless @automatic_reconnect c = new_connection + c.pool = self @connections << c - checkout_and_verify(c) - end - - def checkout_existing_connection - c = (@connections - @checked_out).first - checkout_and_verify(c) + c end def checkout_and_verify(c) c.run_callbacks :checkout do c.verify! - @checked_out << c end c end + + def active_connections + @connections.find_all { |c| c.in_use? } + end end # ConnectionHandler is a collection of ConnectionPool objects. It is used @@ -367,10 +332,12 @@ module ActiveRecord def initialize(pools = {}) @connection_pools = pools + @class_to_pool = {} end def establish_connection(name, spec) - @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec) + @connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec) + @class_to_pool[name] = @connection_pools[spec] end # Returns true if there are any active connections among the connection @@ -421,19 +388,20 @@ module ActiveRecord # can be used as an argument for establish_connection, for easily # re-establishing the connection. def remove_connection(klass) - pool = @connection_pools.delete(klass.name) + pool = @class_to_pool.delete(klass.name) return nil unless pool + @connection_pools.delete pool.spec pool.automatic_reconnect = false pool.disconnect! pool.spec.config end def retrieve_connection_pool(klass) - pool = @connection_pools[klass.name] + pool = @class_to_pool[klass.name] return pool if pool - return nil if ActiveRecord::Base == klass - retrieve_connection_pool klass.superclass + return nil if ActiveRecord::Model == klass + retrieve_connection_pool klass.active_record_super end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb deleted file mode 100644 index c08c0263b9..0000000000 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +++ /dev/null @@ -1,153 +0,0 @@ -module ActiveRecord - class Base - class ConnectionSpecification #:nodoc: - attr_reader :config, :adapter_method - def initialize (config, adapter_method) - @config, @adapter_method = config, adapter_method - end - end - - ## - # :singleton-method: - # The connection handler - class_attribute :connection_handler, :instance_writer => false - self.connection_handler = ConnectionAdapters::ConnectionHandler.new - - # Returns the connection currently associated with the class. This can - # also be used to "borrow" the connection to do database work that isn't - # easily done without going straight to SQL. - def connection - self.class.connection - end - - # Establishes the connection to the database. Accepts a hash as input where - # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case) - # example for regular databases (MySQL, Postgresql, etc): - # - # ActiveRecord::Base.establish_connection( - # :adapter => "mysql", - # :host => "localhost", - # :username => "myuser", - # :password => "mypass", - # :database => "somedatabase" - # ) - # - # Example for SQLite database: - # - # ActiveRecord::Base.establish_connection( - # :adapter => "sqlite", - # :database => "path/to/dbfile" - # ) - # - # Also accepts keys as strings (for parsing from YAML for example): - # - # ActiveRecord::Base.establish_connection( - # "adapter" => "sqlite", - # "database" => "path/to/dbfile" - # ) - # - # Or a URL: - # - # ActiveRecord::Base.establish_connection( - # "postgres://myuser:mypass@localhost/somedatabase" - # ) - # - # The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError - # may be returned on an error. - def self.establish_connection(spec = ENV["DATABASE_URL"]) - case spec - when nil - raise AdapterNotSpecified unless defined?(Rails.env) - establish_connection(Rails.env) - when ConnectionSpecification - self.connection_handler.establish_connection(name, spec) - when Symbol, String - if configuration = configurations[spec.to_s] - establish_connection(configuration) - elsif spec.is_a?(String) && hash = connection_url_to_hash(spec) - establish_connection(hash) - else - raise AdapterNotSpecified, "#{spec} database is not configured" - end - else - spec = spec.symbolize_keys - unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end - - begin - require "active_record/connection_adapters/#{spec[:adapter]}_adapter" - rescue LoadError => e - raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e})" - end - - adapter_method = "#{spec[:adapter]}_connection" - unless respond_to?(adapter_method) - raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter" - end - - remove_connection - establish_connection(ConnectionSpecification.new(spec, adapter_method)) - end - end - - def self.connection_url_to_hash(url) # :nodoc: - config = URI.parse url - adapter = config.scheme - adapter = "postgresql" if adapter == "postgres" - spec = { :adapter => adapter, - :username => config.user, - :password => config.password, - :port => config.port, - :database => config.path.sub(%r{^/},""), - :host => config.host } - spec.reject!{ |_,value| !value } - if config.query - options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys - spec.merge!(options) - end - spec - end - - class << self - # Returns the connection currently associated with the class. This can - # also be used to "borrow" the connection to do database work unrelated - # to any of the specific Active Records. - def connection - retrieve_connection - end - - # Returns the configuration of the associated connection as a hash: - # - # ActiveRecord::Base.connection_config - # # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"} - # - # Please use only for reading. - def connection_config - connection_pool.spec.config - end - - def connection_pool - connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished - end - - def retrieve_connection - connection_handler.retrieve_connection(self) - end - - # Returns true if Active Record is connected. - def connected? - connection_handler.connected?(self) - end - - def remove_connection(klass = self) - connection_handler.remove_connection(klass) - end - - def clear_active_connections! - connection_handler.clear_active_connections! - end - - delegate :clear_reloadable_connections!, - :clear_all_connections!,:verify_active_connections!, :to => :connection_handler - end - end -end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index dc4a53034b..eb8cff9610 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -130,7 +130,7 @@ module ActiveRecord # # In order to get around this problem, #transaction will emulate the effect # of nested transactions, by using savepoints: - # http://dev.mysql.com/doc/refman/5.0/en/savepoints.html + # http://dev.mysql.com/doc/refman/5.0/en/savepoint.html # Savepoints are supported by MySQL and PostgreSQL, but not SQLite3. # # It is safe to call this method if a database transaction is already open, @@ -341,7 +341,7 @@ module ActiveRecord # Send a rollback message to all records after they have been rolled back. If rollback # is false, only rollback records since the last save point. - def rollback_transaction_records(rollback) #:nodoc + def rollback_transaction_records(rollback) if rollback records = @_current_transaction_records.flatten @_current_transaction_records.clear @@ -361,7 +361,7 @@ module ActiveRecord end # Send a commit message to all records after they have been committed. - def commit_transaction_records #:nodoc + def commit_transaction_records records = @_current_transaction_records.flatten @_current_transaction_records.clear unless records.blank? 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 82f564e41d..132ca10f79 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -6,7 +6,7 @@ require 'bigdecimal/util' module ActiveRecord module ConnectionAdapters #:nodoc: - class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc: + class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders) #:nodoc: end # Abstract representation of a column definition. Instances of this type @@ -46,13 +46,13 @@ module ActiveRecord # +change_table+ is actually of this type: # # class SomeMigration < ActiveRecord::Migration - # def self.up + # def up # create_table :foo do |t| # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition" # end # end # - # def self.down + # def down # ... # end # end @@ -66,6 +66,7 @@ module ActiveRecord def initialize(base) @columns = [] + @columns_hash = {} @base = base end @@ -86,7 +87,7 @@ module ActiveRecord # Returns a ColumnDefinition for the column with name +name+. def [](name) - @columns.find {|column| column.name.to_s == name.to_s} + @columns_hash[name.to_s] end # Instantiates a new column for the table. @@ -224,35 +225,38 @@ module ActiveRecord # t.references :taggable, :polymorphic => { :default => 'Photo' } # end def column(name, type, options = {}) - column = self[name] || ColumnDefinition.new(@base, name, type) - if options[:limit] - column.limit = options[:limit] - elsif native[type.to_sym].is_a?(Hash) - column.limit = native[type.to_sym][:limit] + name = name.to_s + type = type.to_sym + + column = self[name] || new_column_definition(@base, name, type) + + limit = options.fetch(:limit) do + native[type][:limit] if native[type].is_a?(Hash) end + + column.limit = limit column.precision = options[:precision] - column.scale = options[:scale] - column.default = options[:default] - column.null = options[:null] - @columns << column unless @columns.include? column + column.scale = options[:scale] + column.default = options[:default] + column.null = options[:null] self end %w( string text integer float decimal datetime timestamp time date binary boolean ).each do |column_type| class_eval <<-EOV, __FILE__, __LINE__ + 1 - def #{column_type}(*args) # def string(*args) - options = args.extract_options! # options = args.extract_options! - column_names = args # column_names = args - # - column_names.each { |name| column(name, '#{column_type}', options) } # column_names.each { |name| column(name, 'string', options) } - end # end + def #{column_type}(*args) # def string(*args) + options = args.extract_options! # options = args.extract_options! + column_names = args # column_names = args + type = :'#{column_type}' # type = :string + column_names.each { |name| column(name, type, options) } # column_names.each { |name| column(name, type, options) } + end # end EOV end # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and # <tt>:updated_at</tt> to the table. def timestamps(*args) - options = args.extract_options! + options = { :null => false }.merge(args.extract_options!) column(:created_at, :datetime, options) column(:updated_at, :datetime, options) end @@ -275,9 +279,16 @@ module ActiveRecord end private - def native - @base.native_database_types - end + def new_column_definition(base, name, type) + definition = ColumnDefinition.new base, name, type + @columns << definition + @columns_hash[name] = definition + definition + end + + def native + @base.native_database_types + end end # Represents an SQL table in an abstract way for updating a table. @@ -453,13 +464,13 @@ module ActiveRecord def #{column_type}(*args) # def string(*args) options = args.extract_options! # options = args.extract_options! column_names = args # column_names = args - # + type = :'#{column_type}' # type = :string column_names.each do |name| # column_names.each do |name| - column = ColumnDefinition.new(@base, name, '#{column_type}') # column = ColumnDefinition.new(@base, name, 'string') + column = ColumnDefinition.new(@base, name.to_s, type) # column = ColumnDefinition.new(@base, name, type) if options[:limit] # if options[:limit] column.limit = options[:limit] # column.limit = options[:limit] - elsif native['#{column_type}'.to_sym].is_a?(Hash) # elsif native['string'.to_sym].is_a?(Hash) - column.limit = native['#{column_type}'.to_sym][:limit] # column.limit = native['string'.to_sym][:limit] + elsif native[type].is_a?(Hash) # elsif native[type].is_a?(Hash) + column.limit = native[type][:limit] # column.limit = native[type][:limit] end # end column.precision = options[:precision] # column.precision = options[:precision] column.scale = options[:scale] # column.scale = options[:scale] @@ -479,4 +490,3 @@ module ActiveRecord end 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 8e3ba1297e..20d3b4a1ef 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/array/wrap' +require 'active_support/deprecation/reporting' module ActiveRecord module ConnectionAdapters # :nodoc: @@ -15,8 +16,6 @@ module ActiveRecord table_name[0...table_alias_length].gsub(/\./, '_') end - # def tables(name = nil) end - # Checks to see if the table +table_name+ exists on the database. # # === Example @@ -113,7 +112,7 @@ module ActiveRecord # Defaults to +id+. If <tt>:id</tt> is false this option is ignored. # # Also note that this just sets the primary key in the table. You additionally - # need to configure the primary key in the model via the +set_primary_key+ macro. + # need to configure the primary key in the model via +self.primary_key=+. # Models do NOT auto-detect the primary key from their table definition. # # [<tt>:options</tt>] @@ -302,15 +301,8 @@ module ActiveRecord # Adds a new index to the table. +column_name+ can be a single Symbol, or # an Array of Symbols. # - # The index will be named after the table and the first column name, - # unless you pass <tt>:name</tt> as an option. - # - # When creating an index on multiple columns, the first column is used as a name - # for the index. For example, when you specify an index on two columns - # [<tt>:first</tt>, <tt>:last</tt>], the DBMS creates an index for both columns as well as an - # index for the first column <tt>:first</tt>. Using just the first name for this index - # makes sense, because you will never have to create a singular index with this - # name. + # The index will be named after the table and the column name(s), unless + # you pass <tt>:name</tt> as an option. # # ===== Examples # @@ -339,6 +331,14 @@ module ActiveRecord # CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) # # Note: SQLite doesn't support index length + # + # ====== Creating an index with a sort order (desc or asc, asc is the default) + # add_index(:accounts, [:branch_id, :party_id, :surname], :order => {:branch_id => :desc, :part_id => :asc}) + # generates + # CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname) + # + # Note: mysql doesn't yet support index order (it accepts the syntax but ignores it) + # def add_index(table_name, column_name, options = {}) index_name, index_type, index_columns = add_index_options(table_name, column_name, options) execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})" @@ -405,7 +405,7 @@ module ActiveRecord def dump_schema_information #:nodoc: sm_table = ActiveRecord::Migrator.schema_migrations_table_name - migrated = select_values("SELECT version FROM #{sm_table}") + migrated = select_values("SELECT version FROM #{sm_table} ORDER BY version") migrated.map { |v| "INSERT INTO #{sm_table} (version) VALUES ('#{v}');" }.join("\n\n") end @@ -426,6 +426,7 @@ module ActiveRecord si_table = Base.table_name_prefix + 'schema_info' + Base.table_name_suffix if table_exists?(si_table) + ActiveRecord::Deprecation.warn "Usage of the schema table `#{si_table}` is deprecated. Please switch to using `schema_migrations` table" old_version = select_value("SELECT version FROM #{quote_table_name(si_table)}").to_i assume_migrated_upto_version(old_version) @@ -507,8 +508,8 @@ module ActiveRecord # ===== Examples # add_timestamps(:suppliers) def add_timestamps(table_name) - add_column table_name, :created_at, :datetime - add_column table_name, :updated_at, :datetime + add_column table_name, :created_at, :datetime, :null => false + add_column table_name, :updated_at, :datetime, :null => false end # Removes the timestamp columns (created_at and updated_at) from the table definition. @@ -520,9 +521,29 @@ module ActiveRecord end protected + def add_index_sort_order(option_strings, column_names, options = {}) + if options.is_a?(Hash) && order = options[:order] + case order + when Hash + column_names.each {|name| option_strings[name] += " #{order[name].to_s.upcase}" if order.has_key?(name)} + when String + column_names.each {|name| option_strings[name] += " #{order.upcase}"} + end + end + + return option_strings + end + # Overridden by the mysql adapter for supporting index lengths def quoted_columns_for_index(column_names, options = {}) - column_names.map {|name| quote_column_name(name) } + option_strings = Hash[column_names.map {|name| [name, '']}] + + # add index sort order if supported + if supports_index_sort_order? + option_strings = add_index_sort_order(option_strings, column_names, options) + end + + column_names.map {|name| quote_column_name(name) + option_strings[name]} end def options_include_default?(options) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 443e61b527..edea414db7 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -3,12 +3,15 @@ require 'bigdecimal' require 'bigdecimal/util' require 'active_support/core_ext/benchmark' require 'active_support/deprecation' +require 'active_record/connection_adapters/schema_cache' +require 'monitor' module ActiveRecord module ConnectionAdapters # :nodoc: extend ActiveSupport::Autoload autoload :Column + autoload :ConnectionSpecification autoload_under 'abstract' do autoload :IndexDefinition, 'active_record/connection_adapters/abstract/schema_definitions' @@ -24,7 +27,6 @@ module ActiveRecord autoload :ConnectionPool autoload :ConnectionHandler, 'active_record/connection_adapters/abstract/connection_pool' autoload :ConnectionManagement, 'active_record/connection_adapters/abstract/connection_pool' - autoload :ConnectionSpecification autoload :QueryCache end @@ -47,39 +49,44 @@ module ActiveRecord include DatabaseLimits include QueryCache include ActiveSupport::Callbacks + include MonitorMixin define_callbacks :checkout, :checkin - attr_accessor :visitor - - def initialize(connection, logger = nil) #:nodoc: - @active = nil - @connection, @logger = connection, logger + attr_accessor :visitor, :pool + attr_reader :schema_cache, :last_use, :in_use + alias :in_use? :in_use + + def initialize(connection, logger = nil, pool = nil) #:nodoc: + super() + + @active = nil + @connection = connection + @in_use = false + @instrumenter = ActiveSupport::Notifications.instrumenter + @last_use = false + @logger = logger + @open_transactions = 0 + @pool = pool + @query_cache = Hash.new { |h,sql| h[sql] = {} } @query_cache_enabled = false - @query_cache = Hash.new { |h,sql| h[sql] = {} } - @open_transactions = 0 - @instrumenter = ActiveSupport::Notifications.instrumenter - @visitor = nil - end - - # Returns a visitor instance for this adaptor, which conforms to the Arel::ToSql interface - def self.visitor_for(pool) # :nodoc: - adapter = pool.spec.config[:adapter] - - if Arel::Visitors::VISITORS[adapter] - ActiveSupport::Deprecation.warn( - "Arel::Visitors::VISITORS is deprecated and will be removed. Database adapters " \ - "should define a visitor_for method which returns the appropriate visitor for " \ - "the database. For example, MysqlAdapter.visitor_for(pool) returns " \ - "Arel::Visitors::MySQL.new(pool)." - ) - - Arel::Visitors::VISITORS[adapter].new(pool) - else - Arel::Visitors::ToSql.new(pool) + @schema_cache = SchemaCache.new self + @visitor = nil + end + + def lease + synchronize do + unless in_use + @in_use = true + @last_use = Time.now + end end end + def expire + @in_use = false + end + # Returns the human-readable name of the adapter. Use mixed case - one # can always use downcase if needed. def adapter_name @@ -130,6 +137,17 @@ module ActiveRecord false end + # Does this adapter support index sort order? + def supports_index_sort_order? + false + end + + # Does this adapter support explain? As of this writing sqlite3, + # mysql2, and postgresql are the only ones that do. + def supports_explain? + false + end + # QUOTING ================================================== # Override to return the quoted table name. Defaults to column quoting. @@ -238,10 +256,19 @@ module ActiveRecord node end + def case_insensitive_comparison(table, attribute, column, value) + table[attribute].lower.eq(table.lower(value)) + end + def current_savepoint_name "active_record_#{open_transactions}" end + # Check the connection back in to the connection pool + def close + pool.checkin self + end + protected def log(sql, name = "SQL", binds = []) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb index 4b7c74e0b8..560773ca86 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -4,6 +4,13 @@ module ActiveRecord module ConnectionAdapters class AbstractMysqlAdapter < AbstractAdapter class Column < ConnectionAdapters::Column # :nodoc: + attr_reader :collation + + def initialize(name, default, sql_type = nil, null = true, collation = nil) + super(name, default, sql_type, null) + @collation = collation + end + def extract_default(default) if sql_type =~ /blob/i || type == :text if default.blank? @@ -28,6 +35,10 @@ module ActiveRecord raise NotImplementedError end + def case_sensitive? + collation && !collation.match(/_ci$/) + end + private def simplified_type(field_type) @@ -116,10 +127,7 @@ module ActiveRecord super(connection, logger) @connection_options, @config = connection_options, config @quoted_column_names, @quoted_table_names = {}, {} - end - - def self.visitor_for(pool) # :nodoc: - Arel::Visitors::MySQL.new(pool) + @visitor = Arel::Visitors::MySQL.new self end def adapter_name #:nodoc: @@ -144,6 +152,12 @@ module ActiveRecord true end + # Technically MySQL allows to create indexes with the sort order syntax + # but at the moment (5.5) it doesn't yet implement them + def supports_index_sort_order? + true + end + def native_database_types NATIVE_DATABASE_TYPES end @@ -157,8 +171,8 @@ module ActiveRecord end # Overridden by the adapters to instantiate their specific Column type. - def new_column(field, default, type, null) # :nodoc: - Column.new(field, default, type, null) + def new_column(field, default, type, null, collation) # :nodoc: + Column.new(field, default, type, null, collation) end # Must return the Mysql error number from the exception, if the exception has an @@ -298,11 +312,11 @@ module ActiveRecord sql = "SHOW TABLES" end - select_all(sql).map do |table| + select_all(sql).map { |table| table.delete('Table_type') sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}" exec_without_stmt(sql).first['Create Table'] + ";\n\n" - end.join("") + }.join end # Drops the database specified on the +name+ attribute @@ -349,8 +363,10 @@ module ActiveRecord show_variable 'collation_database' end - def tables(name = nil, database = nil) #:nodoc: - sql = ["SHOW TABLES", database].compact.join(' IN ') + def tables(name = nil, database = nil, like = nil) #:nodoc: + sql = "SHOW TABLES " + sql << "IN #{database} " if database + sql << "LIKE #{quote(like)}" if like execute_and_free(sql, 'SCHEMA') do |result| result.collect { |field| field.first } @@ -358,7 +374,8 @@ module ActiveRecord end def table_exists?(name) - return true if super + return false unless name + return true if tables(nil, nil, name).any? name = name.to_s schema, table = name.split('.', 2) @@ -368,7 +385,7 @@ module ActiveRecord schema = nil end - tables(nil, schema).include? table + tables(nil, schema, table).any? end # Returns an array of indexes for the given table. @@ -393,10 +410,10 @@ module ActiveRecord # Returns an array of +Column+ objects for the table specified by +table_name+. def columns(table_name, name = nil)#:nodoc: - sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}" + sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}" execute_and_free(sql, 'SCHEMA') do |result| each_hash(result).map do |field| - new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES") + new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES", field[:Collation]) end end end @@ -485,9 +502,14 @@ module ActiveRecord # Returns a table's primary key and belonging sequence. def pk_and_sequence_for(table) - execute_and_free("DESCRIBE #{quote_table_name(table)}", 'SCHEMA') do |result| - keys = each_hash(result).select { |row| row[:Key] == 'PRI' }.map { |row| row[:Field] } - keys.length == 1 ? [keys.first, nil] : nil + execute_and_free("SHOW CREATE TABLE #{quote_table_name(table)}", 'SCHEMA') do |result| + create_table = each_hash(result).first[:"Create Table"] + if create_table.to_s =~ /PRIMARY KEY\s+\((.+)\)/ + keys = $1.split(",").map { |key| key.gsub(/`/, "") } + keys.length == 1 ? [keys.first, nil] : nil + else + nil + end end end @@ -501,23 +523,43 @@ module ActiveRecord Arel::Nodes::Bin.new(node) end + def case_insensitive_comparison(table, attribute, column, value) + if column.case_sensitive? + super + else + table[attribute].eq(value) + end + end + def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) where_sql end protected + def add_index_length(option_strings, column_names, options = {}) + if options.is_a?(Hash) && length = options[:length] + case length + when Hash + column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name)} + when Fixnum + column_names.each {|name| option_strings[name] += "(#{length})"} + end + end + + return option_strings + end + def quoted_columns_for_index(column_names, options = {}) - length = options[:length] if options.is_a?(Hash) + option_strings = Hash[column_names.map {|name| [name, '']}] - case length - when Hash - column_names.map {|name| length[name] ? "#{quote_column_name(name)}(#{length[name]})" : quote_column_name(name) } - when Fixnum - column_names.map {|name| "#{quote_column_name(name)}(#{length})"} - else - column_names.map {|name| quote_column_name(name) } - end + # add index length + option_strings = add_index_length(option_strings, column_names, options) + + # add index sort order + option_strings = add_index_sort_order(option_strings, column_names, options) + + column_names.map {|name| quote_column_name(name) + option_strings[name]} end def translate_exception(exception, message) diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index a7856539b7..6aa4a2c5b3 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -80,9 +80,10 @@ module ActiveRecord when :decimal then klass.value_to_decimal(value) when :datetime, :timestamp then klass.string_to_time(value) when :time then klass.string_to_dummy_time(value) - when :date then klass.string_to_date(value) + when :date then klass.value_to_date(value) when :binary then klass.binary_to_string(value) when :boolean then klass.value_to_boolean(value) + when :hstore then klass.cast_hstore(value) else value end end @@ -97,9 +98,10 @@ module ActiveRecord when :decimal then "#{klass}.value_to_decimal(#{var_name})" when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})" when :time then "#{klass}.string_to_dummy_time(#{var_name})" - when :date then "#{klass}.string_to_date(#{var_name})" + when :date then "#{klass}.value_to_date(#{var_name})" when :binary then "#{klass}.binary_to_string(#{var_name})" when :boolean then "#{klass}.value_to_boolean(#{var_name})" + when :hstore then "#{klass}.cast_hstore(#{var_name})" else var_name end end @@ -132,11 +134,15 @@ module ActiveRecord value end - def string_to_date(string) - return string unless string.is_a?(String) - return nil if string.empty? - - fast_string_to_date(string) || fallback_string_to_date(string) + def value_to_date(value) + if value.is_a?(String) + return nil if value.empty? + fast_string_to_date(value) || fallback_string_to_date(value) + elsif value.respond_to?(:to_date) + value.to_date + else + value + end end def string_to_time(string) diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb new file mode 100644 index 0000000000..8491d42b86 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -0,0 +1,83 @@ +module ActiveRecord + module ConnectionAdapters + class ConnectionSpecification #:nodoc: + attr_reader :config, :adapter_method + + def initialize(config, adapter_method) + @config, @adapter_method = config, adapter_method + end + + def initialize_dup(original) + @config = original.config.dup + end + + ## + # Builds a ConnectionSpecification from user input + class Resolver # :nodoc: + attr_reader :config, :klass, :configurations + + def initialize(config, configurations) + @config = config + @configurations = configurations + end + + def spec + case config + when nil + raise AdapterNotSpecified unless defined?(Rails.env) + resolve_string_connection Rails.env + when Symbol, String + resolve_string_connection config.to_s + when Hash + resolve_hash_connection config + end + end + + private + def resolve_string_connection(spec) # :nodoc: + hash = configurations.fetch(spec) do |k| + connection_url_to_hash(k) + end + + raise(AdapterNotSpecified, "#{spec} database is not configured") unless hash + + resolve_hash_connection hash + end + + def resolve_hash_connection(spec) # :nodoc: + spec = spec.symbolize_keys + + raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter) + + begin + require "active_record/connection_adapters/#{spec[:adapter]}_adapter" + rescue LoadError => e + raise LoadError, "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e.message})", e.backtrace + end + + adapter_method = "#{spec[:adapter]}_connection" + + ConnectionSpecification.new(spec, adapter_method) + end + + def connection_url_to_hash(url) # :nodoc: + config = URI.parse url + adapter = config.scheme + adapter = "postgresql" if adapter == "postgres" + spec = { :adapter => adapter, + :username => config.user, + :password => config.password, + :port => config.port, + :database => config.path.sub(%r{^/},""), + :host => config.host } + spec.reject!{ |_,value| !value } + if config.query + options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys + spec.merge!(options) + end + spec + end + end + end + end +end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 8b574518e5..6086c32dbe 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -1,12 +1,12 @@ require 'active_record/connection_adapters/abstract_mysql_adapter' -gem 'mysql2', '~> 0.3.6' +gem 'mysql2', '~> 0.3.10' require 'mysql2' module ActiveRecord - class Base + module ConnectionHandling # Establishes a connection to the database that's used by all Active Record objects. - def self.mysql2_connection(config) + def mysql2_connection(config) config[:username] = 'root' if config[:username].nil? if Mysql2::Client.const_defined? :FOUND_ROWS @@ -35,6 +35,10 @@ module ActiveRecord configure_connection end + def supports_explain? + true + end + # HELPER METHODS =========================================== def each_hash(result) # :nodoc: @@ -47,8 +51,8 @@ module ActiveRecord end end - def new_column(field, default, type, null) # :nodoc: - Column.new(field, default, type, null) + def new_column(field, default, type, null, collation) # :nodoc: + Column.new(field, default, type, null, collation) end def error_number(exception) @@ -93,6 +97,80 @@ module ActiveRecord # DATABASE STATEMENTS ====================================== + def explain(arel, binds = []) + sql = "EXPLAIN #{to_sql(arel)}" + start = Time.now + result = exec_query(sql, 'EXPLAIN', binds) + elapsed = Time.now - start + + ExplainPrettyPrinter.new.pp(result, elapsed) + end + + class ExplainPrettyPrinter # :nodoc: + # Pretty prints the result of a EXPLAIN in a way that resembles the output of the + # MySQL shell: + # + # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ + # | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | + # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ + # | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | | + # | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where | + # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ + # 2 rows in set (0.00 sec) + # + # This is an exercise in Ruby hyperrealism :). + def pp(result, elapsed) + widths = compute_column_widths(result) + separator = build_separator(widths) + + pp = [] + + pp << separator + pp << build_cells(result.columns, widths) + pp << separator + + result.rows.each do |row| + pp << build_cells(row, widths) + end + + pp << separator + pp << build_footer(result.rows.length, elapsed) + + pp.join("\n") + "\n" + end + + private + + def compute_column_widths(result) + [].tap do |widths| + result.columns.each_with_index do |column, i| + cells_in_column = [column] + result.rows.map {|r| r[i].nil? ? 'NULL' : r[i].to_s} + widths << cells_in_column.map(&:length).max + end + end + end + + def build_separator(widths) + padding = 1 + '+' + widths.map {|w| '-' * (w + (padding*2))}.join('+') + '+' + end + + def build_cells(items, widths) + cells = [] + items.each_with_index do |item, i| + item = 'NULL' if item.nil? + justifier = item.is_a?(Numeric) ? 'rjust' : 'ljust' + cells << item.to_s.send(justifier, widths[i]) + end + '| ' + cells.join(' | ') + ' |' + end + + def build_footer(nrows, elapsed) + rows_label = nrows == 1 ? 'row' : 'rows' + "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed + end + end + # FIXME: re-enable the following once a "better" query_cache solution is in core # # The overrides below perform much better than the originals in AbstractAdapter diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index a1824fe396..e432c5af32 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -18,9 +18,9 @@ class Mysql end module ActiveRecord - class Base + module ConnectionHandling # Establishes a connection to the database that's used by all Active Record objects. - def self.mysql_connection(config) # :nodoc: + def mysql_connection(config) # :nodoc: config = config.symbolize_keys host = config[:host] port = config[:port] @@ -150,8 +150,8 @@ module ActiveRecord end end - def new_column(field, default, type, null) # :nodoc: - Column.new(field, default, type, null) + def new_column(field, default, type, null, collation) # :nodoc: + Column.new(field, default, type, null, collation) end def error_number(exception) # :nodoc: @@ -224,52 +224,48 @@ module ActiveRecord @statements.clear end - if "<3".respond_to?(:encode) - # Taken from here: - # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb - # Author: TOMITA Masahiro <tommy@tmtm.org> - ENCODINGS = { - "armscii8" => nil, - "ascii" => Encoding::US_ASCII, - "big5" => Encoding::Big5, - "binary" => Encoding::ASCII_8BIT, - "cp1250" => Encoding::Windows_1250, - "cp1251" => Encoding::Windows_1251, - "cp1256" => Encoding::Windows_1256, - "cp1257" => Encoding::Windows_1257, - "cp850" => Encoding::CP850, - "cp852" => Encoding::CP852, - "cp866" => Encoding::IBM866, - "cp932" => Encoding::Windows_31J, - "dec8" => nil, - "eucjpms" => Encoding::EucJP_ms, - "euckr" => Encoding::EUC_KR, - "gb2312" => Encoding::EUC_CN, - "gbk" => Encoding::GBK, - "geostd8" => nil, - "greek" => Encoding::ISO_8859_7, - "hebrew" => Encoding::ISO_8859_8, - "hp8" => nil, - "keybcs2" => nil, - "koi8r" => Encoding::KOI8_R, - "koi8u" => Encoding::KOI8_U, - "latin1" => Encoding::ISO_8859_1, - "latin2" => Encoding::ISO_8859_2, - "latin5" => Encoding::ISO_8859_9, - "latin7" => Encoding::ISO_8859_13, - "macce" => Encoding::MacCentEuro, - "macroman" => Encoding::MacRoman, - "sjis" => Encoding::SHIFT_JIS, - "swe7" => nil, - "tis620" => Encoding::TIS_620, - "ucs2" => Encoding::UTF_16BE, - "ujis" => Encoding::EucJP_ms, - "utf8" => Encoding::UTF_8, - "utf8mb4" => Encoding::UTF_8, - } - else - ENCODINGS = Hash.new { |h,k| h[k] = k } - end + # Taken from here: + # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb + # Author: TOMITA Masahiro <tommy@tmtm.org> + ENCODINGS = { + "armscii8" => nil, + "ascii" => Encoding::US_ASCII, + "big5" => Encoding::Big5, + "binary" => Encoding::ASCII_8BIT, + "cp1250" => Encoding::Windows_1250, + "cp1251" => Encoding::Windows_1251, + "cp1256" => Encoding::Windows_1256, + "cp1257" => Encoding::Windows_1257, + "cp850" => Encoding::CP850, + "cp852" => Encoding::CP852, + "cp866" => Encoding::IBM866, + "cp932" => Encoding::Windows_31J, + "dec8" => nil, + "eucjpms" => Encoding::EucJP_ms, + "euckr" => Encoding::EUC_KR, + "gb2312" => Encoding::EUC_CN, + "gbk" => Encoding::GBK, + "geostd8" => nil, + "greek" => Encoding::ISO_8859_7, + "hebrew" => Encoding::ISO_8859_8, + "hp8" => nil, + "keybcs2" => nil, + "koi8r" => Encoding::KOI8_R, + "koi8u" => Encoding::KOI8_U, + "latin1" => Encoding::ISO_8859_1, + "latin2" => Encoding::ISO_8859_2, + "latin5" => Encoding::ISO_8859_9, + "latin7" => Encoding::ISO_8859_13, + "macce" => Encoding::MacCentEuro, + "macroman" => Encoding::MacRoman, + "sjis" => Encoding::SHIFT_JIS, + "swe7" => nil, + "tis620" => Encoding::TIS_620, + "ucs2" => Encoding::UTF_16BE, + "ujis" => Encoding::EucJP_ms, + "utf8" => Encoding::UTF_8, + "utf8mb4" => Encoding::UTF_8, + } # Get the client encoding for this database def client_encoding diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 5402918b1d..d2361b5378 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -7,9 +7,9 @@ gem 'pg', '~> 0.11' require 'pg' module ActiveRecord - class Base + module ConnectionHandling # Establishes a connection to the database that's used by all Active Record objects - def self.postgresql_connection(config) # :nodoc: + def postgresql_connection(config) # :nodoc: config = config.symbolize_keys host = config[:host] port = config[:port] || 5432 @@ -49,6 +49,42 @@ module ActiveRecord super end end + + def cast_hstore(object) + if Hash === object + object.map { |k,v| + "#{escape_hstore(k)}=>#{escape_hstore(v)}" + }.join ', ' + else + kvs = object.scan(/(?<!\\)".*?(?<!\\)"/).map { |o| + unescape_hstore(o[1...-1]) + } + Hash[kvs.each_slice(2).to_a] + end + end + + private + HSTORE_ESCAPE = { + ' ' => '\\ ', + '\\' => '\\\\', + '"' => '\\"', + '=' => '\\=', + } + HSTORE_ESCAPE_RE = Regexp.union(HSTORE_ESCAPE.keys) + HSTORE_UNESCAPE = HSTORE_ESCAPE.invert + HSTORE_UNESCAPE_RE = Regexp.union(HSTORE_UNESCAPE.keys) + + def unescape_hstore(value) + value.gsub(HSTORE_UNESCAPE_RE) do |match| + HSTORE_UNESCAPE[match] + end + end + + def escape_hstore(value) + value.gsub(HSTORE_ESCAPE_RE) do |match| + HSTORE_ESCAPE[match] + end + end end # :startdoc: @@ -79,53 +115,55 @@ module ActiveRecord # Maps PostgreSQL-specific data types to logical Rails types. def simplified_type(field_type) case field_type - # Numeric and monetary types - when /^(?:real|double precision)$/ - :float - # Monetary types - when 'money' - :decimal - # Character types - when /^(?:character varying|bpchar)(?:\(\d+\))?$/ - :string - # Binary data types - when 'bytea' - :binary - # Date/time types - when /^timestamp with(?:out)? time zone$/ - :datetime - when 'interval' - :string - # Geometric types - when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/ - :string - # Network address types - when /^(?:cidr|inet|macaddr)$/ - :string - # Bit strings - when /^bit(?: varying)?(?:\(\d+\))?$/ - :string - # XML type - when 'xml' - :xml - # tsvector type - when 'tsvector' - :tsvector - # Arrays - when /^\D+\[\]$/ - :string - # Object identifier types - when 'oid' - :integer - # UUID type - when 'uuid' - :string - # Small and big integer types - when /^(?:small|big)int$/ - :integer - # Pass through all types that are not specific to PostgreSQL. - else - super + # Numeric and monetary types + when /^(?:real|double precision)$/ + :float + # Monetary types + when 'money' + :decimal + when 'hstore' + :hstore + # Character types + when /^(?:character varying|bpchar)(?:\(\d+\))?$/ + :string + # Binary data types + when 'bytea' + :binary + # Date/time types + when /^timestamp with(?:out)? time zone$/ + :datetime + when 'interval' + :string + # Geometric types + when /^(?:point|line|lseg|box|"?path"?|polygon|circle)$/ + :string + # Network address types + when /^(?:cidr|inet|macaddr)$/ + :string + # Bit strings + when /^bit(?: varying)?(?:\(\d+\))?$/ + :string + # XML type + when 'xml' + :xml + # tsvector type + when 'tsvector' + :tsvector + # Arrays + when /^\D+\[\]$/ + :string + # Object identifier types + when 'oid' + :integer + # UUID type + when 'uuid' + :string + # Small and big integer types + when /^(?:small|big)int$/ + :integer + # Pass through all types that are not specific to PostgreSQL. + else + super end end @@ -215,6 +253,10 @@ module ActiveRecord options = args.extract_options! column(args[0], 'tsvector', options) end + + def hstore(name, options = {}) + column(name, 'hstore', options) + end end ADAPTER_NAME = 'PostgreSQL' @@ -247,6 +289,10 @@ module ActiveRecord true end + def supports_index_sort_order? + true + end + class StatementPool < ConnectionAdapters::StatementPool def initialize(connection, max) super @@ -278,13 +324,24 @@ module ActiveRecord cache.clear end + def delete(sql_key) + dealloc cache[sql_key] + cache.delete sql_key + end + private def cache @cache[$$] end def dealloc(key) - @connection.query "DEALLOCATE #{key}" + @connection.query "DEALLOCATE #{key}" if connection_active? + end + + def connection_active? + @connection.status == PGconn::CONNECTION_OK + rescue PGError + false end end @@ -292,6 +349,7 @@ module ActiveRecord def initialize(connection, logger, connection_parameters, config) super(connection, logger) @connection_parameters, @config = connection_parameters, config + @visitor = Arel::Visitors::PostgreSQL.new self # @local_tz is initialized as nil to avoid warnings when connect tries to use it @local_tz = nil @@ -308,10 +366,6 @@ module ActiveRecord @local_tz = execute('SHOW TIME ZONE', 'SCHEMA').first["TimeZone"] end - def self.visitor_for(pool) # :nodoc: - Arel::Visitors::PostgreSQL.new(pool) - end - # Clears the prepared statements cache. def clear_cache! @statements.clear @@ -378,6 +432,11 @@ module ActiveRecord true end + # Returns true. + def supports_explain? + true + end + # Returns the configured supported identifier length supported by PostgreSQL def table_alias_length @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i @@ -502,6 +561,48 @@ module ActiveRecord # DATABASE STATEMENTS ====================================== + def explain(arel, binds = []) + sql = "EXPLAIN #{to_sql(arel)}" + ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds)) + end + + class ExplainPrettyPrinter # :nodoc: + # Pretty prints the result of a EXPLAIN in a way that resembles the output of the + # PostgreSQL shell: + # + # QUERY PLAN + # ------------------------------------------------------------------------------ + # Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0) + # Join Filter: (posts.user_id = users.id) + # -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4) + # Index Cond: (id = 1) + # -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4) + # Filter: (posts.user_id = 1) + # (6 rows) + # + def pp(result) + header = result.columns.first + lines = result.rows.map(&:first) + + # We add 2 because there's one char of padding at both sides, note + # the extra hyphens in the example above. + width = [header, *lines].map(&:length).max + 2 + + pp = [] + + pp << header.center(width).rstrip + pp << '-' * width + + pp += lines.map {|line| " #{line}"} + + nrows = result.rows.length + rows_label = nrows == 1 ? 'row' : 'rows' + pp << "(#{nrows} #{rows_label})" + + pp.join("\n") + "\n" + end + end + # Executes a SELECT query and returns an array of rows. Each row is an # array of field values. def select_rows(sql, name = nil) @@ -743,16 +844,15 @@ module ActiveRecord # Returns an array of indexes for the given table. def indexes(table_name, name = nil) - schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',') result = query(<<-SQL, name) - SELECT distinct i.relname, d.indisunique, d.indkey, t.oid + SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid FROM pg_class t INNER JOIN pg_index d ON t.oid = d.indrelid INNER JOIN pg_class i ON d.indexrelid = i.oid WHERE i.relkind = 'i' AND d.indisprimary = 'f' AND t.relname = '#{table_name}' - AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (#{schemas}) ) + AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) ) ORDER BY i.relname SQL @@ -761,7 +861,8 @@ module ActiveRecord index_name = row[0] unique = row[1] == 't' indkey = row[2].split(" ") - oid = row[3] + inddef = row[3] + oid = row[4] columns = Hash[query(<<-SQL, "Columns for index #{row[0]} on #{table_name}")] SELECT a.attnum, a.attname @@ -771,7 +872,12 @@ module ActiveRecord SQL column_names = columns.values_at(*indkey).compact - column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names) + + # add info on sort order for columns (only desc order is explicitly specified, asc is the default) + desc_order_columns = inddef.scan(/(\w+) DESC/).flatten + orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {} + + column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names, [], orders) end.compact end @@ -815,7 +921,7 @@ module ActiveRecord # Returns the active schema search path. def schema_search_path - @schema_search_path ||= query('SHOW search_path')[0][0] + @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0] end # Returns the current client message level. @@ -911,12 +1017,14 @@ module ActiveRecord # Example: # rename_table('octopuses', 'octopi') def rename_table(name, new_name) + clear_cache! execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}" end # Adds a new column to the named table. # See TableDefinition#column for details of the options you can use. def add_column(table_name, column_name, type, options = {}) + clear_cache! add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(add_column_sql, options) @@ -925,6 +1033,7 @@ module ActiveRecord # Changes the column of a table. def change_column(table_name, column_name, type, options = {}) + clear_cache! quoted_table_name = quote_table_name(table_name) execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" @@ -935,10 +1044,12 @@ module ActiveRecord # Changes the default value of a table column. def change_column_default(table_name, column_name, default) + clear_cache! execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}" end def change_column_null(table_name, column_name, null, default = nil) + clear_cache! unless null || default.nil? execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end @@ -947,6 +1058,7 @@ module ActiveRecord # Renames a column in a table. def rename_column(table_name, column_name, new_column_name) + clear_cache! execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}" end @@ -1030,26 +1142,54 @@ module ActiveRecord end private + FEATURE_NOT_SUPPORTED = "0A000" # :nodoc: + def exec_no_cache(sql, binds) @connection.async_exec(sql) end def exec_cache(sql, binds) - unless @statements.key? sql - nextkey = @statements.next_key - @connection.prepare nextkey, sql - @statements[sql] = nextkey + begin + stmt_key = prepare_statement sql + + # Clear the queue + @connection.get_last_result + @connection.send_query_prepared(stmt_key, binds.map { |col, val| + type_cast(val, col) + }) + @connection.block + @connection.get_last_result + rescue PGError => e + # Get the PG code for the failure. Annoyingly, the code for + # prepared statements whose return value may have changed is + # FEATURE_NOT_SUPPORTED. Check here for more details: + # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573 + code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE) + if FEATURE_NOT_SUPPORTED == code + @statements.delete sql_key(sql) + retry + else + raise e + end end + end - key = @statements[sql] + # Returns the statement identifier for the client side cache + # of statements + def sql_key(sql) + "#{schema_search_path}-#{sql}" + end - # Clear the queue - @connection.get_last_result - @connection.send_query_prepared(key, binds.map { |col, val| - type_cast(val, col) - }) - @connection.block - @connection.get_last_result + # Prepare the statement if it hasn't been prepared, return + # the statement key. + def prepare_statement(sql) + sql_key = sql_key(sql) + unless @statements.key? sql_key + nextkey = @statements.next_key + @connection.prepare nextkey, sql + @statements[sql_key] = nextkey + end + @statements[sql_key] end # The internal PostgreSQL identifier of the money data type. diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb new file mode 100644 index 0000000000..4e8932a695 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb @@ -0,0 +1,50 @@ +module ActiveRecord + module ConnectionAdapters + class SchemaCache + attr_reader :columns, :columns_hash, :primary_keys, :tables + attr_reader :connection + + def initialize(conn) + @connection = conn + @tables = {} + + @columns = Hash.new do |h, table_name| + h[table_name] = conn.columns(table_name, "#{table_name} Columns") + end + + @columns_hash = Hash.new do |h, table_name| + h[table_name] = Hash[columns[table_name].map { |col| + [col.name, col] + }] + end + + @primary_keys = Hash.new do |h, table_name| + h[table_name] = table_exists?(table_name) ? conn.primary_key(table_name) : nil + end + end + + # A cached lookup for table existence. + def table_exists?(name) + return @tables[name] if @tables.key? name + + @tables[name] = connection.table_exists?(name) + end + + # Clears out internal caches + def clear! + @columns.clear + @columns_hash.clear + @primary_keys.clear + @tables.clear + end + + # Clear out internal caches for table with +table_name+. + def clear_table_cache!(table_name) + @columns.delete table_name + @columns_hash.delete table_name + @primary_keys.delete table_name + @tables.delete table_name + end + end + end +end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 0a0da0b5d3..ee5d10859c 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -1,12 +1,12 @@ require 'active_record/connection_adapters/sqlite_adapter' -gem 'sqlite3', '~> 1.3.4' +gem 'sqlite3', '~> 1.3.5' require 'sqlite3' module ActiveRecord - class Base + module ConnectionHandling # sqlite3 adapter reuses sqlite_connection. - def self.sqlite3_connection(config) # :nodoc: + def sqlite3_connection(config) # :nodoc: # Require database. unless config[:database] raise ArgumentError, "No database file specified. Missing argument: database" @@ -47,11 +47,7 @@ module ActiveRecord # Returns the current database encoding format as a string, eg: 'UTF-8' def encoding - if @connection.respond_to?(:encoding) - @connection.encoding.to_s - else - @connection.execute('PRAGMA encoding')[0]['encoding'] - end + @connection.encoding.to_s end end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb index 1932a849ee..69750a911d 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb @@ -16,7 +16,7 @@ module ActiveRecord end def binary_to_string(value) - if value.respond_to?(:force_encoding) && value.encoding != Encoding::ASCII_8BIT + if value.encoding != Encoding::ASCII_8BIT value = value.force_encoding(Encoding::ASCII_8BIT) end @@ -89,10 +89,7 @@ module ActiveRecord @statements = StatementPool.new(@connection, config.fetch(:statement_limit) { 1000 }) @config = config - end - - def self.visitor_for(pool) # :nodoc: - Arel::Visitors::SQLite.new(pool) + @visitor = Arel::Visitors::SQLite.new self end def adapter_name #:nodoc: @@ -125,6 +122,11 @@ module ActiveRecord true end + # Returns true. + def supports_explain? + true + end + def requires_reloading? true end @@ -157,6 +159,10 @@ module ActiveRecord sqlite_version >= '3.1.0' end + def supports_index_sort_order? + sqlite_version >= '3.3.0' + end + def native_database_types #:nodoc: { :primary_key => default_primary_key_type, @@ -195,29 +201,40 @@ module ActiveRecord end end - if "<3".encoding_aware? - def type_cast(value, column) # :nodoc: - return value.to_f if BigDecimal === value - return super unless String === value - return super unless column && value - - value = super - if column.type == :string && value.encoding == Encoding::ASCII_8BIT - @logger.error "Binary data inserted for `string` type on column `#{column.name}`" - value.encode! 'utf-8' - end - value - end - else - def type_cast(value, column) # :nodoc: - return super unless BigDecimal === value + def type_cast(value, column) # :nodoc: + return value.to_f if BigDecimal === value + return super unless String === value + return super unless column && value - value.to_f + value = super + if column.type == :string && value.encoding == Encoding::ASCII_8BIT + @logger.error "Binary data inserted for `string` type on column `#{column.name}`" + value.encode! 'utf-8' end + value end # DATABASE STATEMENTS ====================================== + def explain(arel, binds = []) + sql = "EXPLAIN QUERY PLAN #{to_sql(arel)}" + ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds)) + end + + class ExplainPrettyPrinter + # Pretty prints the result of a EXPLAIN QUERY PLAN in a way that resembles + # the output of the SQLite shell: + # + # 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows) + # 0|1|1|SCAN TABLE posts (~100000 rows) + # + def pp(result) # :nodoc: + result.rows.map do |row| + row.join('|') + end.join("\n") + "\n" + end + end + def exec_query(sql, name = nil, binds = []) log(sql, name, binds) do @@ -304,18 +321,23 @@ module ActiveRecord # SCHEMA STATEMENTS ======================================== - def tables(name = 'SCHEMA') #:nodoc: + def tables(name = 'SCHEMA', table_name = nil) #:nodoc: sql = <<-SQL SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence' SQL + sql << " AND name = #{quote_table_name(table_name)}" if table_name exec_query(sql, name).map do |row| row['name'] end end + def table_exists?(name) + name && tables('SCHEMA', name).any? + end + # Returns an array of +SQLiteColumn+ objects for the table specified by +table_name+. def columns(table_name, name = nil) #:nodoc: table_structure(table_name).map do |field| @@ -413,6 +435,8 @@ module ActiveRecord self.limit = options[:limit] if options.include?(:limit) self.default = options[:default] if include_default self.null = options[:null] if options.include?(:null) + self.precision = options[:precision] if options.include?(:precision) + self.scale = options[:scale] if options.include?(:scale) end end end @@ -467,6 +491,7 @@ module ActiveRecord @definition.column(column_name, column.type, :limit => column.limit, :default => column.default, + :precision => column.precision, :scale => column.scale, :null => column.null) end @definition.primary_key(primary_key(from)) if primary_key(from) diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb new file mode 100644 index 0000000000..e9cd3d5e57 --- /dev/null +++ b/activerecord/lib/active_record/connection_handling.rb @@ -0,0 +1,100 @@ +require 'active_support/core_ext/module/delegation' + +module ActiveRecord + module ConnectionHandling + # Establishes the connection to the database. Accepts a hash as input where + # the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case) + # example for regular databases (MySQL, Postgresql, etc): + # + # ActiveRecord::Base.establish_connection( + # :adapter => "mysql", + # :host => "localhost", + # :username => "myuser", + # :password => "mypass", + # :database => "somedatabase" + # ) + # + # Example for SQLite database: + # + # ActiveRecord::Base.establish_connection( + # :adapter => "sqlite", + # :database => "path/to/dbfile" + # ) + # + # Also accepts keys as strings (for parsing from YAML for example): + # + # ActiveRecord::Base.establish_connection( + # "adapter" => "sqlite", + # "database" => "path/to/dbfile" + # ) + # + # Or a URL: + # + # ActiveRecord::Base.establish_connection( + # "postgres://myuser:mypass@localhost/somedatabase" + # ) + # + # The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError + # may be returned on an error. + def establish_connection(spec = ENV["DATABASE_URL"]) + resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new spec, configurations + spec = resolver.spec + + unless respond_to?(spec.adapter_method) + raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter" + end + + remove_connection + connection_handler.establish_connection name, spec + end + + # Returns the connection currently associated with the class. This can + # also be used to "borrow" the connection to do database work unrelated + # to any of the specific Active Records. + def connection + retrieve_connection + end + + def connection_id + Thread.current['ActiveRecord::Base.connection_id'] + end + + def connection_id=(connection_id) + Thread.current['ActiveRecord::Base.connection_id'] = connection_id + end + + # Returns the configuration of the associated connection as a hash: + # + # ActiveRecord::Base.connection_config + # # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"} + # + # Please use only for reading. + def connection_config + connection_pool.spec.config + end + + def connection_pool + connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished + end + + def retrieve_connection + connection_handler.retrieve_connection(self) + end + + # Returns true if Active Record is connected. + def connected? + connection_handler.connected?(self) + end + + def remove_connection(klass = self) + connection_handler.remove_connection(klass) + end + + def clear_active_connections! + connection_handler.clear_active_connections! + end + + delegate :clear_reloadable_connections!, + :clear_all_connections!,:verify_active_connections!, :to => :connection_handler + end +end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb new file mode 100644 index 0000000000..980f8fe50f --- /dev/null +++ b/activerecord/lib/active_record/core.rb @@ -0,0 +1,354 @@ +require 'active_support/concern' + +module ActiveRecord + module Core + extend ActiveSupport::Concern + + included do + ## + # :singleton-method: + # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, + # which is then passed on to any new database connections made and which can be retrieved on both + # a class and instance level by calling +logger+. + config_attribute :logger, :global => true + + ## + # :singleton-method: + # Contains the database configuration - as is typically stored in config/database.yml - + # as a Hash. + # + # For example, the following database.yml... + # + # development: + # adapter: sqlite3 + # database: db/development.sqlite3 + # + # production: + # adapter: sqlite3 + # database: db/production.sqlite3 + # + # ...would result in ActiveRecord::Base.configurations to look like this: + # + # { + # 'development' => { + # 'adapter' => 'sqlite3', + # 'database' => 'db/development.sqlite3' + # }, + # 'production' => { + # 'adapter' => 'sqlite3', + # 'database' => 'db/production.sqlite3' + # } + # } + config_attribute :configurations, :global => true + self.configurations = {} + + ## + # :singleton-method: + # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling + # dates and times from the database. This is set to :local by default. + config_attribute :default_timezone, :global => true + self.default_timezone = :local + + ## + # :singleton-method: + # Specifies the format to use when dumping the database schema with Rails' + # Rakefile. If :sql, the schema is dumped as (potentially database- + # specific) SQL statements. If :ruby, the schema is dumped as an + # ActiveRecord::Schema file which can be loaded into any database that + # supports migrations. Use :ruby if you want to have different database + # adapters for, e.g., your development and test environments. + config_attribute :schema_format, :global => true + self.schema_format = :ruby + + ## + # :singleton-method: + # Specify whether or not to use timestamps for migration versions + config_attribute :timestamped_migrations, :global => true + self.timestamped_migrations = true + + ## + # :singleton-method: + # The connection handler + config_attribute :connection_handler + self.connection_handler = ConnectionAdapters::ConnectionHandler.new + end + + module ClassMethods + def inherited(child_class) #:nodoc: + child_class.initialize_generated_modules + super + end + + def initialize_generated_modules + # force attribute methods to be higher in inheritance hierarchy than other generated methods + generated_attribute_methods + generated_feature_methods + end + + def generated_feature_methods + @generated_feature_methods ||= begin + mod = const_set(:GeneratedFeatureMethods, Module.new) + include mod + mod + end + end + + # Returns a string like 'Post(id:integer, title:string, body:text)' + def inspect + if self == Base + super + elsif abstract_class? + "#{super}(abstract)" + elsif table_exists? + attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', ' + "#{super}(#{attr_list})" + else + "#{super}(Table doesn't exist)" + end + end + + # Overwrite the default class equality method to provide support for association proxies. + def ===(object) + object.is_a?(self) + end + + def arel_table + @arel_table ||= Arel::Table.new(table_name, arel_engine) + end + + def arel_engine + @arel_engine ||= connection_handler.connection_pools[name] ? self : active_record_super.arel_engine + end + + private + + def relation #:nodoc: + @relation ||= Relation.new(self, arel_table) + + if finder_needs_type_condition? + @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) + else + @relation + end + end + end + + # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with + # attributes but not yet saved (pass a hash with key names matching the associated table column names). + # In both instances, valid attribute keys are determined by the column names of the associated table -- + # hence you can't have attributes that aren't part of the table columns. + # + # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options + # in the +options+ parameter. + # + # ==== Examples + # # Instantiates a single new object + # User.new(:first_name => 'Jamie') + # + # # Instantiates a single new object using the :admin mass-assignment security role + # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) + # + # # Instantiates a single new object bypassing mass-assignment security + # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) + def initialize(attributes = nil, options = {}) + @attributes = self.class.initialize_attributes(self.class.column_defaults.dup) + @association_cache = {} + @aggregation_cache = {} + @attributes_cache = {} + @new_record = true + @readonly = false + @destroyed = false + @marked_for_destruction = false + @previously_changed = {} + @changed_attributes = {} + @relation = nil + + ensure_proper_type + + populate_with_current_scope_attributes + + assign_attributes(attributes, options) if attributes + + yield self if block_given? + run_callbacks :initialize + end + + # Initialize an empty model object from +coder+. +coder+ must contain + # the attributes necessary for initializing an empty model object. For + # example: + # + # class Post < ActiveRecord::Base + # end + # + # post = Post.allocate + # post.init_with('attributes' => { 'title' => 'hello world' }) + # post.title # => 'hello world' + def init_with(coder) + @attributes = self.class.initialize_attributes(coder['attributes']) + @relation = nil + + @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {} + @association_cache = {} + @aggregation_cache = {} + @readonly = @destroyed = @marked_for_destruction = false + @new_record = false + run_callbacks :find + run_callbacks :initialize + + self + end + + # Duped objects have no id assigned and are treated as new records. Note + # that this is a "shallow" copy as it copies the object's attributes + # only, not its associations. The extent of a "deep" copy is application + # specific and is therefore left to the application to implement according + # to its need. + # The dup method does not preserve the timestamps (created|updated)_(at|on). + def initialize_dup(other) + cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast) + cloned_attributes.delete(self.class.primary_key) + + @attributes = cloned_attributes + + _run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks) + + @changed_attributes = {} + self.class.column_defaults.each do |attr, orig_value| + @changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr]) + end + + @aggregation_cache = {} + @association_cache = {} + @attributes_cache = {} + @new_record = true + + ensure_proper_type + populate_with_current_scope_attributes + super + end + + # Populate +coder+ with attributes about this record that should be + # serialized. The structure of +coder+ defined in this method is + # guaranteed to match the structure of +coder+ passed to the +init_with+ + # method. + # + # Example: + # + # class Post < ActiveRecord::Base + # end + # coder = {} + # Post.new.encode_with(coder) + # coder # => { 'id' => nil, ... } + def encode_with(coder) + coder['attributes'] = attributes + end + + # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ + # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+. + # + # Note that new records are different from any other record by definition, unless the + # other record is the receiver itself. Besides, if you fetch existing records with + # +select+ and leave the ID out, you're on your own, this predicate will return false. + # + # Note also that destroying a record preserves its ID in the model instance, so deleted + # models are still comparable. + def ==(comparison_object) + super || + comparison_object.instance_of?(self.class) && + id.present? && + comparison_object.id == id + end + alias :eql? :== + + # Delegates to id in order to allow two records of the same type and id to work with something like: + # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] + def hash + id.hash + end + + # Freeze the attributes hash such that associations are still accessible, even on destroyed records. + def freeze + @attributes.freeze; self + end + + # Returns +true+ if the attributes hash has been frozen. + def frozen? + @attributes.frozen? + end + + # Allows sort on objects + def <=>(other_object) + if other_object.is_a?(self.class) + self.to_key <=> other_object.to_key + else + nil + end + end + + # Returns +true+ if the record is read only. Records loaded through joins with piggy-back + # attributes will be marked as read only since they cannot be saved. + def readonly? + @readonly + end + + # Marks this record as read only. + def readonly! + @readonly = true + end + + # Returns the connection currently associated with the class. This can + # also be used to "borrow" the connection to do database work that isn't + # easily done without going straight to SQL. + def connection + self.class.connection + end + + # Returns the contents of the record as a nicely formatted string. + def inspect + inspection = if @attributes + self.class.column_names.collect { |name| + if has_attribute?(name) + "#{name}: #{attribute_for_inspect(name)}" + end + }.compact.join(", ") + else + "not initialized" + end + "#<#{self.class} #{inspection}>" + end + + # Hackery to accomodate Syck. Remove for 4.0. + def to_yaml(opts = {}) #:nodoc: + if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? + super + else + coder = {} + encode_with(coder) + YAML.quick_emit(self, opts) do |out| + out.map(taguri, to_yaml_style) do |map| + coder.each { |k, v| map.add(k, v) } + end + end + end + end + + # Hackery to accomodate Syck. Remove for 4.0. + def yaml_initialize(tag, coder) #:nodoc: + init_with(coder) + end + + private + + # Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements + # of the array, and then rescues from the possible NoMethodError. If those elements are + # ActiveRecord::Base's, then this triggers the various method_missing's that we have, + # which significantly impacts upon performance. + # + # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here. + # + # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/ + def to_ary # :nodoc: + nil + end + end +end diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb index 3c7defedac..031918712a 100644 --- a/activerecord/lib/active_record/counter_cache.rb +++ b/activerecord/lib/active_record/counter_cache.rb @@ -65,7 +65,7 @@ module ActiveRecord # Post.update_counters [10, 15], :comment_count => 1 # # Executes the following SQL: # # UPDATE posts - # # SET comment_count = COALESCE(comment_count, 0) + 1, + # # SET comment_count = COALESCE(comment_count, 0) + 1 # # WHERE id IN (10, 15) def update_counters(id, counters) updates = counters.map do |counter_name, value| diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb new file mode 100644 index 0000000000..e9068089f0 --- /dev/null +++ b/activerecord/lib/active_record/dynamic_matchers.rb @@ -0,0 +1,79 @@ +module ActiveRecord + module DynamicMatchers + def respond_to?(method_id, include_private = false) + if match = DynamicFinderMatch.match(method_id) + return true if all_attributes_exists?(match.attribute_names) + elsif match = DynamicScopeMatch.match(method_id) + return true if all_attributes_exists?(match.attribute_names) + end + + super + end + + private + + # Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and + # <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders + # section at the top of this file for more detailed information. + # + # It's even possible to use all the additional parameters to +find+. For example, the + # full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>. + # + # Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it + # is first invoked, so that future attempts to use it do not run through method_missing. + def method_missing(method_id, *arguments, &block) + if match = (DynamicFinderMatch.match(method_id) || DynamicScopeMatch.match(method_id)) + attribute_names = match.attribute_names + super unless all_attributes_exists?(attribute_names) + if arguments.size < attribute_names.size + method_trace = "#{__FILE__}:#{__LINE__}:in `#{method_id}'" + backtrace = [method_trace] + caller + raise ArgumentError, "wrong number of arguments (#{arguments.size} for #{attribute_names.size})", backtrace + end + if match.respond_to?(:scope?) && match.scope? + self.class_eval <<-METHOD, __FILE__, __LINE__ + 1 + def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args) + attributes = Hash[[:#{attribute_names.join(',:')}].zip(args)] # attributes = Hash[[:user_name, :password].zip(args)] + # + scoped(:conditions => attributes) # scoped(:conditions => attributes) + end # end + METHOD + send(method_id, *arguments) + elsif match.finder? + options = arguments.extract_options! + relation = options.any? ? scoped(options) : scoped + relation.send :find_by_attributes, match, attribute_names, *arguments, &block + elsif match.instantiator? + scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block + end + else + super + end + end + + # Similar in purpose to +expand_hash_conditions_for_aggregates+. + def expand_attribute_names_for_aggregates(attribute_names) + attribute_names.map { |attribute_name| + unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? + aggregate_mapping(aggregation).map do |field_attr, _| + field_attr.to_sym + end + else + attribute_name.to_sym + end + }.flatten + end + + def all_attributes_exists?(attribute_names) + (expand_attribute_names_for_aggregates(attribute_names) - + column_methods_hash.keys).empty? + end + + def aggregate_mapping(reflection) + mapping = reflection.options[:mapping] || [reflection.name, reflection.name] + mapping.first.is_a?(Array) ? mapping : [mapping] + end + + + end +end diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index 8262b60f6e..fc80f3081e 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -99,6 +99,16 @@ module ActiveRecord # # Read more about optimistic locking in ActiveRecord::Locking module RDoc. class StaleObjectError < ActiveRecordError + attr_reader :record, :attempted_action + + def initialize(record, attempted_action) + @record = record + @attempted_action = attempted_action + end + + def message + "Attempted to #{attempted_action} a stale object: #{record.class.name}" + end end # Raised when association is being configured improperly or @@ -170,8 +180,7 @@ module ActiveRecord end end - # Raised when a model attempts to fetch its primary key from the database, but the table - # has no primary key declared. + # Raised when a primary key is needed, but there is not one specified in the schema or model. class UnknownPrimaryKey < ActiveRecordError attr_reader :model diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb new file mode 100644 index 0000000000..e502d7e52b --- /dev/null +++ b/activerecord/lib/active_record/explain.rb @@ -0,0 +1,80 @@ +require 'active_support/core_ext/class/attribute' + +module ActiveRecord + module Explain + def self.extended(base) + # If a query takes longer than these many seconds we log its query plan + # automatically. nil disables this feature. + base.config_attribute :auto_explain_threshold_in_seconds, :global => true + end + + # If auto explain is enabled, this method triggers EXPLAIN logging for the + # queries triggered by the block if it takes more than the threshold as a + # whole. That is, the threshold is not checked against each individual + # query, but against the duration of the entire block. This approach is + # convenient for relations. + # + # The available_queries_for_explain thread variable collects the queries + # to be explained. If the value is nil, it means queries are not being + # currently collected. A false value indicates collecting is turned + # off. Otherwise it is an array of queries. + def logging_query_plan # :nodoc: + threshold = auto_explain_threshold_in_seconds + current = Thread.current + if threshold && current[:available_queries_for_explain].nil? + begin + queries = current[:available_queries_for_explain] = [] + start = Time.now + result = yield + logger.warn(exec_explain(queries)) if Time.now - start > threshold + result + ensure + current[:available_queries_for_explain] = nil + end + else + yield + end + end + + # Relation#explain needs to be able to collect the queries regardless of + # whether auto explain is enabled. This method serves that purpose. + def collecting_queries_for_explain # :nodoc: + current = Thread.current + original, current[:available_queries_for_explain] = current[:available_queries_for_explain], [] + return yield, current[:available_queries_for_explain] + ensure + # Note that the return value above does not depend on this assigment. + current[:available_queries_for_explain] = original + end + + # Makes the adapter execute EXPLAIN for the tuples of queries and bindings. + # Returns a formatted string ready to be logged. + def exec_explain(queries) # :nodoc: + queries && queries.map do |sql, bind| + [].tap do |msg| + msg << "EXPLAIN for: #{sql}" + unless bind.empty? + bind_msg = bind.map {|col, val| [col.name, val]}.inspect + msg.last << " #{bind_msg}" + end + msg << connection.explain(sql, bind) + end.join("\n") + end.join("\n") + end + + # Silences automatic EXPLAIN logging for the duration of the block. + # + # This has high priority, no EXPLAINs will be run even if downwards + # the threshold is set to 0. + # + # As the name of the method suggests this only applies to automatic + # EXPLAINs, manual calls to +ActiveRecord::Relation#explain+ run. + def silence_auto_explain + current = Thread.current + original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false + yield + ensure + current[:available_queries_for_explain] = original + end + end +end diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb new file mode 100644 index 0000000000..fc76410499 --- /dev/null +++ b/activerecord/lib/active_record/explain_subscriber.rb @@ -0,0 +1,21 @@ +require 'active_support/notifications' + +module ActiveRecord + class ExplainSubscriber # :nodoc: + def call(*args) + if queries = Thread.current[:available_queries_for_explain] + payload = args.last + queries << payload.values_at(:sql, :binds) unless ignore_payload?(payload) + end + end + + # SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on + # our own EXPLAINs now matter how loopingly beautiful that would be. + IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN) + def ignore_payload?(payload) + payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) + end + + ActiveSupport::Notifications.subscribe("sql.active_record", new) + end +end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 97af15c9e8..c59c00f424 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -10,7 +10,6 @@ require 'zlib' require 'active_support/dependencies' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/logger' require 'active_support/ordered_hash' require 'active_record/fixtures/file' @@ -22,8 +21,6 @@ else end end -class FixturesFileNotFound < StandardError; end - module ActiveRecord # \Fixtures are a way of organizing data that you want to test against; in short, sample data. # @@ -391,10 +388,15 @@ module ActiveRecord @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} } - def self.find_table_name(table_name) # :nodoc: + def self.default_fixture_model_name(fixture_name) # :nodoc: ActiveRecord::Base.pluralize_table_names ? - table_name.to_s.singularize.camelize : - table_name.to_s.camelize + fixture_name.singularize.camelize : + fixture_name.camelize + end + + def self.default_fixture_table_name(fixture_name) # :nodoc: + "#{ActiveRecord::Base.table_name_prefix}"\ + "#{fixture_name.tr('/', '_')}#{ActiveRecord::Base.table_name_suffix}".to_sym end def self.reset_cache @@ -444,9 +446,6 @@ module ActiveRecord def self.create_fixtures(fixtures_directory, table_names, class_names = {}) table_names = [table_names].flatten.map { |n| n.to_s } - table_names.each { |n| - class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/') - } # FIXME: Apparently JK uses this. connection = block_given? ? yield : ActiveRecord::Base.connection @@ -460,12 +459,12 @@ module ActiveRecord fixtures_map = {} fixture_files = files_to_read.map do |path| - table_name = path.tr '/', '_' + fixture_name = path - fixtures_map[path] = ActiveRecord::Fixtures.new( + fixtures_map[fixture_name] = new( # ActiveRecord::Fixtures.new connection, - table_name, - class_names[table_name.to_sym] || table_name.classify, + fixture_name, + class_names[fixture_name] || default_fixture_model_name(fixture_name), ::File.join(fixtures_directory, path)) end @@ -489,8 +488,8 @@ module ActiveRecord # Cap primary key sequences to max(pk). if connection.respond_to?(:reset_pk_sequence!) - table_names.each do |table_name| - connection.reset_pk_sequence!(table_name.tr('/', '_')) + fixture_files.each do |ff| + connection.reset_pk_sequence!(ff.table_name) end end end @@ -509,25 +508,27 @@ module ActiveRecord attr_reader :table_name, :name, :fixtures, :model_class - def initialize(connection, table_name, class_name, fixture_path) + def initialize(connection, fixture_name, class_name, fixture_path) @connection = connection - @table_name = table_name @fixture_path = fixture_path - @name = table_name # preserve fixture base name + @name = fixture_name @class_name = class_name @fixtures = ActiveSupport::OrderedHash.new - @table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}" # Should be an AR::Base type class if class_name.is_a?(Class) - @table_name = class_name.table_name - @connection = class_name.connection - @model_class = class_name + @model_class = class_name else - @model_class = class_name.constantize rescue nil + @model_class = class_name.constantize rescue nil end + @connection = model_class.connection if model_class && model_class.respond_to?(:connection) + + @table_name = ( model_class.respond_to?(:table_name) ? + model_class.table_name : + self.class.default_fixture_table_name(fixture_name) ) + read_fixture_files end @@ -562,7 +563,7 @@ module ActiveRecord rows[table_name] = fixtures.map do |label, fixture| row = fixture.to_hash - if model_class && model_class < ActiveRecord::Base + if model_class && model_class < ActiveRecord::Model # fill in timestamp columns if they aren't specified and the model is set to record_timestamps if model_class.record_timestamps timestamp_column_names.each do |name| @@ -622,7 +623,7 @@ module ActiveRecord private def primary_key_name - @primary_key_name ||= model_class && model_class.primary_key? && model_class.primary_key + @primary_key_name ||= model_class && model_class.primary_key end def has_primary_key_column? @@ -644,14 +645,6 @@ module ActiveRecord end def read_fixture_files - if ::File.file?(yaml_file_path) - read_yaml_fixture_files - else - raise FixturesFileNotFound, "Could not find #{yaml_file_path}" - end - end - - def read_yaml_fixture_files yaml_files = Dir["#{@fixture_path}/**/*.yml"].select { |f| ::File.file?(f) } + [yaml_file_path] @@ -734,14 +727,29 @@ module ActiveRecord self.use_instantiated_fixtures = false self.pre_loaded_fixtures = false - self.fixture_class_names = Hash.new do |h, table_name| - h[table_name] = ActiveRecord::Fixtures.find_table_name(table_name) + self.fixture_class_names = Hash.new do |h, fixture_name| + h[fixture_name] = ActiveRecord::Fixtures.default_fixture_model_name(fixture_name) end end module ClassMethods + # Sets the model class for a fixture when the class name cannot be inferred from the fixture name. + # + # Examples: + # + # set_fixture_class :some_fixture => SomeModel, + # 'namespaced/fixture' => Another::Model + # + # The keys must be the fixture names, that coincide with the short paths to the fixture files. + #-- + # It is also possible to pass the class name instead of the class: + # set_fixture_class 'some_fixture' => 'SomeModel' + # I think this option is redundant, i propose to deprecate it. + # Isn't it easier to always pass the class itself? + # (2011-12-20 alexeymuranov) + #++ def set_fixture_class(class_names = {}) - self.fixture_class_names = self.fixture_class_names.merge(class_names) + self.fixture_class_names = self.fixture_class_names.merge(class_names.stringify_keys) end def fixtures(*fixture_names) @@ -781,9 +789,9 @@ module ActiveRecord fixture_names = Array.wrap(fixture_names || fixture_table_names) methods = Module.new do fixture_names.each do |fixture_name| - fixture_name = fixture_name.to_s.tr('./', '_') + accessor_name = fixture_name.tr('/', '_').to_sym - define_method(fixture_name) do |*fixtures| + define_method(accessor_name) do |*fixtures| force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload @fixture_cache[fixture_name] ||= {} @@ -796,13 +804,13 @@ module ActiveRecord @fixture_cache[fixture_name][fixture] ||= @loaded_fixtures[fixture_name][fixture.to_s].find end else - raise StandardError, "No fixture with name '#{fixture}' found for table '#{fixture_name}'" + raise StandardError, "No entry named '#{fixture}' found for fixture collection '#{fixture_name}'" end end instances.size == 1 ? instances.first : instances end - private fixture_name + private accessor_name end end include methods @@ -832,6 +840,7 @@ module ActiveRecord end @fixture_cache = {} + @fixture_connections = [] @@already_loaded_fixtures ||= {} # Load fixtures once and begin transaction. @@ -842,9 +851,12 @@ module ActiveRecord @loaded_fixtures = load_fixtures @@already_loaded_fixtures[self.class] = @loaded_fixtures end - ActiveRecord::Base.connection.increment_open_transactions - ActiveRecord::Base.connection.transaction_joinable = false - ActiveRecord::Base.connection.begin_db_transaction + @fixture_connections = enlist_fixture_connections + @fixture_connections.each do |connection| + connection.increment_open_transactions + connection.transaction_joinable = false + connection.begin_db_transaction + end # Load fixtures for every test. else ActiveRecord::Fixtures.reset_cache @@ -864,13 +876,22 @@ module ActiveRecord end # Rollback changes if a transaction is active. - if run_in_transaction? && ActiveRecord::Base.connection.open_transactions != 0 - ActiveRecord::Base.connection.rollback_db_transaction - ActiveRecord::Base.connection.decrement_open_transactions + if run_in_transaction? + @fixture_connections.each do |connection| + if connection.open_transactions != 0 + connection.rollback_db_transaction + connection.decrement_open_transactions + end + end + @fixture_connections.clear end ActiveRecord::Base.clear_active_connections! end + def enlist_fixture_connections + ActiveRecord::Base.connection_handler.connection_pools.values.map(&:connection) + end + private def load_fixtures fixtures = ActiveRecord::Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names) diff --git a/activerecord/lib/active_record/identity_map.rb b/activerecord/lib/active_record/identity_map.rb index b15b5a8133..680d9ffea0 100644 --- a/activerecord/lib/active_record/identity_map.rb +++ b/activerecord/lib/active_record/identity_map.rb @@ -111,13 +111,12 @@ module ActiveRecord # model object. def reinit_with(coder) @attributes_cache = {} - dirty = @changed_attributes.keys - @attributes.update(coder['attributes'].except(*dirty)) + dirty = @changed_attributes.keys + attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty)) + @attributes.update(attributes) @changed_attributes.update(coder['attributes'].slice(*dirty)) @changed_attributes.delete_if{|k,v| v.eql? @attributes[k]} - set_serialized_attributes - run_callbacks :find self diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb new file mode 100644 index 0000000000..eaa7deac5a --- /dev/null +++ b/activerecord/lib/active_record/inheritance.rb @@ -0,0 +1,182 @@ +require 'active_support/concern' + +module ActiveRecord + module Inheritance + extend ActiveSupport::Concern + + included do + # Determine whether to store the full constant name including namespace when using STI + config_attribute :store_full_sti_class + self.store_full_sti_class = true + end + + module ClassMethods + # True if this isn't a concrete subclass needing a STI type condition. + def descends_from_active_record? + sup = active_record_super + + if sup.abstract_class? + sup.descends_from_active_record? + elsif self == Base + false + else + [Base, Model].include?(sup) || !columns_hash.include?(inheritance_column) + end + end + + def finder_needs_type_condition? #:nodoc: + # This is like this because benchmarking justifies the strange :false stuff + :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) + end + + def symbolized_base_class + @symbolized_base_class ||= base_class.to_s.to_sym + end + + def symbolized_sti_name + @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class + end + + # Returns the base AR subclass that this class descends from. If A + # extends AR::Base, A.base_class will return A. If B descends from A + # through some arbitrarily deep hierarchy, B.base_class will return A. + # + # If B < A and C < B and if A is an abstract_class then both B.base_class + # and C.base_class would return B as the answer since A is an abstract_class. + def base_class + class_of_active_record_descendant(self) + end + + # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). + attr_accessor :abstract_class + + # Returns whether this class is an abstract class or not. + def abstract_class? + defined?(@abstract_class) && @abstract_class == true + end + + def sti_name + store_full_sti_class ? name : name.demodulize + end + + # Finder methods must instantiate through this method to work with the + # single-table inheritance model that makes it possible to create + # objects of different types from the same table. + def instantiate(record) + sti_class = find_sti_class(record[inheritance_column]) + record_id = sti_class.primary_key && record[sti_class.primary_key] + + if ActiveRecord::IdentityMap.enabled? && record_id + if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number? + record_id = record_id.to_i + end + if instance = IdentityMap.get(sti_class, record_id) + instance.reinit_with('attributes' => record) + else + instance = sti_class.allocate.init_with('attributes' => record) + IdentityMap.add(instance) + end + else + instance = sti_class.allocate.init_with('attributes' => record) + end + + instance + end + + # For internal use. + # + # If this class includes ActiveRecord::Model then it won't have a + # superclass. So this provides a way to get to the 'root' (ActiveRecord::Model). + def active_record_super #:nodoc: + superclass < Model ? superclass : Model + end + + protected + + # Returns the class descending directly from ActiveRecord::Base or an + # abstract class, if any, in the inheritance hierarchy. + def class_of_active_record_descendant(klass) + unless klass < Model + raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" + end + + sup = klass.active_record_super + if [Base, Model].include?(klass) || [Base, Model].include?(sup) || sup.abstract_class? + klass + else + class_of_active_record_descendant(sup) + end + end + + # Returns the class type of the record using the current module as a prefix. So descendants of + # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. + def compute_type(type_name) + if type_name.match(/^::/) + # If the type is prefixed with a scope operator then we assume that + # the type_name is an absolute reference. + ActiveSupport::Dependencies.constantize(type_name) + else + # Build a list of candidates to search for + candidates = [] + name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } + candidates << type_name + + candidates.each do |candidate| + begin + constant = ActiveSupport::Dependencies.constantize(candidate) + return constant if candidate == constant.to_s + rescue NameError => e + # We don't want to swallow NoMethodError < NameError errors + raise e unless e.instance_of?(NameError) + end + end + + raise NameError, "uninitialized constant #{candidates.first}" + end + end + + private + + def find_sti_class(type_name) + if type_name.blank? || !columns_hash.include?(inheritance_column) + self + else + begin + if store_full_sti_class + ActiveSupport::Dependencies.constantize(type_name) + else + compute_type(type_name) + end + rescue NameError + raise SubclassNotFound, + "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " + + "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + + "Please rename this column if you didn't intend it to be used for storing the inheritance class " + + "or overwrite #{name}.inheritance_column to use another column for that information." + end + end + end + + def type_condition(table = arel_table) + sti_column = table[inheritance_column.to_sym] + sti_names = ([self] + descendants).map { |model| model.sti_name } + + sti_column.in(sti_names) + end + end + + private + + # Sets the attribute used for single table inheritance to this class name if this is not the + # ActiveRecord::Base descendant. + # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to + # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. + # No such attribute would be set for objects of the Message class in that example. + def ensure_proper_type + klass = self.class + if klass.finder_needs_type_condition? + write_attribute(klass.inheritance_column, klass.sti_name) + end + end + end +end diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb new file mode 100644 index 0000000000..2c42f4cca5 --- /dev/null +++ b/activerecord/lib/active_record/integration.rb @@ -0,0 +1,49 @@ +module ActiveRecord + module Integration + # Returns a String, which Action Pack uses for constructing an URL to this + # object. The default implementation returns this record's id as a String, + # or nil if this record's unsaved. + # + # For example, suppose that you have a User model, and that you have a + # <tt>resources :users</tt> route. Normally, +user_path+ will + # construct a path with the user object's 'id' in it: + # + # user = User.find_by_name('Phusion') + # user_path(user) # => "/users/1" + # + # You can override +to_param+ in your model to make +user_path+ construct + # a path using the user's name instead of the user's id: + # + # class User < ActiveRecord::Base + # def to_param # overridden + # name + # end + # end + # + # user = User.find_by_name('Phusion') + # user_path(user) # => "/users/Phusion" + def to_param + # We can't use alias_method here, because method 'id' optimizes itself on the fly. + id && id.to_s # Be sure to stringify the id for routes + end + + # Returns a cache key that can be used to identify this record. + # + # ==== Examples + # + # Product.new.cache_key # => "products/new" + # Product.find(5).cache_key # => "products/5" (updated_at not available) + # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available) + def cache_key + case + when new_record? + "#{self.class.model_name.cache_key}/new" + when timestamp = self[:updated_at] + timestamp = timestamp.utc.to_s(:number) + "#{self.class.model_name.cache_key}/#{id}-#{timestamp}" + else + "#{self.class.model_name.cache_key}/#{id}" + end + end + end +end diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index d9ad7e4132..e643c0d437 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -37,6 +37,9 @@ module ActiveRecord # You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, # or otherwise apply the business logic needed to resolve the conflict. # + # This locking mechanism will function inside a single Ruby process. To make it work across all + # web requests, the recommended approach is to add +lock_version+ as a hidden field to your form. + # # You must ensure that your database schema defaults the +lock_version+ column to 0. # # This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>. @@ -46,12 +49,8 @@ module ActiveRecord extend ActiveSupport::Concern included do - cattr_accessor :lock_optimistically, :instance_writer => false + config_attribute :lock_optimistically, :global => true self.lock_optimistically = true - - class << self - alias_method :locking_column=, :set_locking_column - end end def locking_enabled? #:nodoc: @@ -65,21 +64,6 @@ module ActiveRecord send(lock_col + '=', previous_lock_value + 1) end - def attributes_from_column_definition - result = super - - # If the locking column has no default value set, - # start the lock version at zero. Note we can't use - # <tt>locking_enabled?</tt> at this point as - # <tt>@attributes</tt> may not have been initialized yet. - - if result.key?(self.class.locking_column) && lock_optimistically - result[self.class.locking_column] ||= 0 - end - - result - end - def update(attribute_names = @attributes.keys) #:nodoc: return super unless locking_enabled? return 0 if attribute_names.empty? @@ -103,7 +87,7 @@ module ActiveRecord affected_rows = connection.update stmt unless affected_rows == 1 - raise ActiveRecord::StaleObjectError, "Attempted to update a stale object: #{self.class.name}" + raise ActiveRecord::StaleObjectError.new(self, "update") end affected_rows @@ -127,7 +111,7 @@ module ActiveRecord affected_rows = self.class.unscoped.where(predicate).delete_all unless affected_rows == 1 - raise ActiveRecord::StaleObjectError, "Attempted to delete a stale object: #{self.class.name}" + raise ActiveRecord::StaleObjectError.new(self, "destroy") end end @@ -146,14 +130,15 @@ module ActiveRecord end # Set the column to use for optimistic locking. Defaults to +lock_version+. - def set_locking_column(value = nil, &block) - define_attr_method :locking_column, value, &block - value + def locking_column=(value) + @original_locking_column = @locking_column if defined?(@locking_column) + @locking_column = value.to_s end # The version column used for optimistic locking. Defaults to +lock_version+. def locking_column - reset_locking_column + reset_locking_column unless defined?(@locking_column) + @locking_column end # Quote the column name used for optimistic locking. @@ -163,7 +148,7 @@ module ActiveRecord # Reset the column used for optimistic locking back to the +lock_version+ default. def reset_locking_column - set_locking_column DEFAULT_LOCKING_COLUMN + self.locking_column = DEFAULT_LOCKING_COLUMN end # Make sure the lock version column gets updated when counters are @@ -172,6 +157,18 @@ module ActiveRecord counters = counters.merge(locking_column => 1) if locking_enabled? super end + + # If the locking column has no default value set, + # start the lock version at zero. Note we can't use + # <tt>locking_enabled?</tt> at this point as + # <tt>@attributes</tt> may not have been initialized yet. + def initialize_attributes(attributes) #:nodoc: + if attributes.key?(locking_column) && lock_optimistically + attributes[locking_column] ||= 0 + end + + attributes + end end end end diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb index 3a015ee8c2..a25f2c7bca 100644 --- a/activerecord/lib/active_record/log_subscriber.rb +++ b/activerecord/lib/active_record/log_subscriber.rb @@ -26,9 +26,9 @@ module ActiveRecord return if 'SCHEMA' == payload[:name] - name = '%s (%.1fms)' % [payload[:name], event.duration] - sql = payload[:sql].squeeze(' ') - binds = nil + name = '%s (%.1fms)' % [payload[:name], event.duration] + sql = payload[:sql].squeeze(' ') + binds = nil unless (payload[:binds] || []).empty? binds = " " + payload[:binds].map { |col,v| diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 7166f1b82a..46464783fd 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -112,12 +112,13 @@ module ActiveRecord # a column but keeps the type and content. # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes # the column to a different type using the same parameters as add_column. - # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named - # +column_name+ from the table called +table_name+. + # * <tt>remove_column(table_name, column_names)</tt>: Removes the column listed in + # +column_names+ from the table called +table_name+. # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index # with the name of the column. Other options include - # <tt>:name</tt> and <tt>:unique</tt> (e.g. - # <tt>{ :name => "users_name_index", :unique => true }</tt>). + # <tt>:name</tt>, <tt>:unique</tt> (e.g. + # <tt>{ :name => "users_name_index", :unique => true }</tt>) and <tt>:order</tt> + # (e.g. { :order => {:name => :desc} }</tt>). # * <tt>remove_index(table_name, :column => column_name)</tt>: Removes the index # specified by +column_name+. # * <tt>remove_index(table_name, :name => index_name)</tt>: Removes the index @@ -301,7 +302,7 @@ module ActiveRecord # # class TenderloveMigration < ActiveRecord::Migration # def change - # create_table(:horses) do + # create_table(:horses) do |t| # t.column :content, :text # t.column :remind_at, :datetime # end @@ -442,6 +443,7 @@ module ActiveRecord say_with_time "#{method}(#{arg_list})" do unless arguments.empty? || method == :execute arguments[0] = Migrator.proper_table_name(arguments.first) + arguments[1] = Migrator.proper_table_name(arguments.second) if method == :rename_table end return super unless connection.respond_to?(method) connection.send(method, *arguments, &block) @@ -455,26 +457,28 @@ module ActiveRecord destination_migrations = ActiveRecord::Migrator.migrations(destination) last = destination_migrations.last - sources.each do |name, path| + sources.each do |scope, path| source_migrations = ActiveRecord::Migrator.migrations(path) source_migrations.each do |migration| source = File.read(migration.filename) - source = "# This migration comes from #{name} (originally #{migration.version})\n#{source}" + source = "# This migration comes from #{scope} (originally #{migration.version})\n#{source}" if duplicate = destination_migrations.detect { |m| m.name == migration.name } - options[:on_skip].call(name, migration) if File.read(duplicate.filename) != source && options[:on_skip] + if options[:on_skip] && duplicate.scope != scope.to_s + options[:on_skip].call(scope, migration) + end next end migration.version = next_migration_number(last ? last.version + 1 : 0).to_i - new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.rb") + new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb") old_path, migration.filename = migration.filename, new_path last = migration - FileUtils.cp(old_path, migration.filename) + File.open(migration.filename, "w") { |f| f.write source } copied << migration - options[:on_copy].call(name, migration, old_path) if options[:on_copy] + options[:on_copy].call(scope, migration, old_path) if options[:on_copy] destination_migrations << migration end end @@ -493,9 +497,9 @@ module ActiveRecord # MigrationProxy is used to defer loading of the actual migration classes # until they are needed - class MigrationProxy < Struct.new(:name, :version, :filename) + class MigrationProxy < Struct.new(:name, :version, :filename, :scope) - def initialize(name, version, filename) + def initialize(name, version, filename, scope) super @migration = nil end @@ -524,16 +528,16 @@ module ActiveRecord attr_writer :migrations_paths alias :migrations_path= :migrations_paths= - def migrate(migrations_paths, target_version = nil) + def migrate(migrations_paths, target_version = nil, &block) case when target_version.nil? - up(migrations_paths, target_version) + up(migrations_paths, target_version, &block) when current_version == 0 && target_version == 0 [] when current_version > target_version - down(migrations_paths, target_version) + down(migrations_paths, target_version, &block) else - up(migrations_paths, target_version) + up(migrations_paths, target_version, &block) end end @@ -545,12 +549,12 @@ module ActiveRecord move(:up, migrations_paths, steps) end - def up(migrations_paths, target_version = nil) - self.new(:up, migrations_paths, target_version).migrate + def up(migrations_paths, target_version = nil, &block) + self.new(:up, migrations_paths, target_version).migrate(&block) end - def down(migrations_paths, target_version = nil) - self.new(:down, migrations_paths, target_version).migrate + def down(migrations_paths, target_version = nil, &block) + self.new(:down, migrations_paths, target_version).migrate(&block) end def run(direction, migrations_paths, target_version) @@ -590,15 +594,16 @@ module ActiveRecord migrations_paths.first end - def migrations(paths) + def migrations(paths, subdirectories = true) paths = Array.wrap(paths) - files = Dir[*paths.map { |p| "#{p}/[0-9]*_*.rb" }] + glob = subdirectories ? "**/" : "" + files = Dir[*paths.map { |p| "#{p}/#{glob}[0-9]*_*.rb" }] seen = Hash.new false migrations = files.map do |file| - version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first + version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?.rb/).first raise IllegalMigrationNameError.new(file) unless version version = version.to_i @@ -609,7 +614,7 @@ module ActiveRecord seen[version] = seen[name] = true - MigrationProxy.new(name, version, file) + MigrationProxy.new(name, version, file, scope) end migrations.sort_by(&:version) @@ -652,7 +657,7 @@ module ActiveRecord end end - def migrate + def migrate(&block) current = migrations.detect { |m| m.version == current_version } target = migrations.detect { |m| m.version == @target_version } @@ -669,6 +674,10 @@ module ActiveRecord ran = [] runnable.each do |migration| + if block && !block.call(migration) + next + end + Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger seen = migrated.include?(migration.version.to_i) diff --git a/activerecord/lib/active_record/model.rb b/activerecord/lib/active_record/model.rb new file mode 100644 index 0000000000..86de5ab2fa --- /dev/null +++ b/activerecord/lib/active_record/model.rb @@ -0,0 +1,109 @@ +require 'active_support/deprecation' + +module ActiveRecord + # <tt>ActiveRecord::Model</tt> can be included into a class to add Active Record persistence. + # This is an alternative to inheriting from <tt>ActiveRecord::Base</tt>. Example: + # + # class Post + # include ActiveRecord::Model + # end + # + module Model + module ClassMethods #:nodoc: + include ActiveSupport::Callbacks::ClassMethods + include ActiveModel::Naming + include QueryCache::ClassMethods + include ActiveSupport::Benchmarkable + include ActiveSupport::DescendantsTracker + + include Querying + include Translation + include DynamicMatchers + include CounterCache + include Explain + include ConnectionHandling + end + + def self.included(base) + return if base.singleton_class < ClassMethods + + base.class_eval do + extend ClassMethods + Callbacks::Register.setup(self) + initialize_generated_modules unless self == Base + end + end + + extend ActiveModel::Configuration + extend ActiveModel::Callbacks + extend ActiveModel::MassAssignmentSecurity::ClassMethods + extend ActiveModel::AttributeMethods::ClassMethods + extend Callbacks::Register + extend Explain + extend ConnectionHandling + + def self.extend(*modules) + ClassMethods.send(:include, *modules) + end + + include Persistence + include ReadonlyAttributes + include ModelSchema + include Inheritance + include Scoping + include Sanitization + include Integration + include AttributeAssignment + include ActiveModel::Conversion + include Validations + include Locking::Optimistic, Locking::Pessimistic + include AttributeMethods + include Callbacks, ActiveModel::Observing, Timestamp + include Associations + include IdentityMap + include ActiveModel::SecurePassword + include AutosaveAssociation, NestedAttributes + include Aggregations, Transactions, Reflection, Serialization, Store + include Core + + class << self + def arel_engine + self + end + + def abstract_class? + false + end + + def inheritance_column + 'type' + end + end + + module DeprecationProxy #:nodoc: + class << self + instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$|^instance_eval$/ } + + def method_missing(name, *args, &block) + if Model.respond_to?(name) + Model.send(name, *args, &block) + else + ActiveSupport::Deprecation.warn( + "The object passed to the active_record load hook was previously ActiveRecord::Base " \ + "(a Class). Now it is ActiveRecord::Model (a Module). You have called `#{name}' which " \ + "is only defined on ActiveRecord::Base. Please change your code so that it works with " \ + "a module rather than a class. (Model is included in Base, so anything added to Model " \ + "will be available on Base as well.)" + ) + Base.send(name, *args, &block) + end + end + + alias send method_missing + end + end + end + + # Load Base at this point, because the active_record load hook is run in that file. + Base +end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb new file mode 100644 index 0000000000..c1a8583119 --- /dev/null +++ b/activerecord/lib/active_record/model_schema.rb @@ -0,0 +1,303 @@ +require 'active_support/concern' +require 'active_support/core_ext/class/attribute_accessors' + +module ActiveRecord + module ModelSchema + extend ActiveSupport::Concern + + included do + ## + # :singleton-method: + # Accessor for the prefix type that will be prepended to every primary key column name. + # The options are :table_name and :table_name_with_underscore. If the first is specified, + # the Product class will look for "productid" instead of "id" as the primary column. If the + # latter is specified, the Product class will look for "product_id" instead of "id". Remember + # that this is a global setting for all Active Records. + config_attribute :primary_key_prefix_type, :global => true + + ## + # :singleton-method: + # Accessor for the name of the prefix string to prepend to every table name. So if set + # to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people", + # etc. This is a convenient way of creating a namespace for tables in a shared database. + # By default, the prefix is the empty string. + # + # If you are organising your models within modules you can add a prefix to the models within + # a namespace by defining a singleton method in the parent module called table_name_prefix which + # returns your chosen prefix. + config_attribute :table_name_prefix + self.table_name_prefix = "" + + ## + # :singleton-method: + # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", + # "people_basecamp"). By default, the suffix is the empty string. + config_attribute :table_name_suffix + self.table_name_suffix = "" + + ## + # :singleton-method: + # Indicates whether table names should be the pluralized versions of the corresponding class names. + # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. + # See table_name for the full rules on table/class naming. This is true, by default. + config_attribute :pluralize_table_names + self.pluralize_table_names = true + end + + module ClassMethods + # Guesses the table name (in forced lower-case) based on the name of the class in the + # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy + # looks like: Reply < Message < ActiveRecord::Base, then Message is used + # to guess the table name even when called on Reply. The rules used to do the guess + # are handled by the Inflector class in Active Support, which knows almost all common + # English inflections. You can add new inflections in config/initializers/inflections.rb. + # + # Nested classes are given table names prefixed by the singular form of + # the parent's table name. Enclosing modules are not considered. + # + # ==== Examples + # + # class Invoice < ActiveRecord::Base + # end + # + # file class table_name + # invoice.rb Invoice invoices + # + # class Invoice < ActiveRecord::Base + # class Lineitem < ActiveRecord::Base + # end + # end + # + # file class table_name + # invoice.rb Invoice::Lineitem invoice_lineitems + # + # module Invoice + # class Lineitem < ActiveRecord::Base + # end + # end + # + # file class table_name + # invoice/lineitem.rb Invoice::Lineitem lineitems + # + # Additionally, the class-level +table_name_prefix+ is prepended and the + # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, + # the table name guess for an Invoice class becomes "myapp_invoices". + # Invoice::Lineitem becomes "myapp_invoice_lineitems". + # + # You can also set your own table name explicitly: + # + # class Mouse < ActiveRecord::Base + # self.table_name = "mice" + # end + # + # Alternatively, you can override the table_name method to define your + # own computation. (Possibly using <tt>super</tt> to manipulate the default + # table name.) Example: + # + # class Post < ActiveRecord::Base + # def self.table_name + # "special_" + super + # end + # end + # Post.table_name # => "special_posts" + def table_name + reset_table_name unless defined?(@table_name) + @table_name + end + + # Sets the table name explicitly. Example: + # + # class Project < ActiveRecord::Base + # self.table_name = "project" + # end + # + # You can also just define your own <tt>self.table_name</tt> method; see + # the documentation for ActiveRecord::Base#table_name. + def table_name=(value) + @original_table_name = @table_name if defined?(@table_name) + @table_name = value + @quoted_table_name = nil + @arel_table = nil + @relation = Relation.new(self, arel_table) + end + + # Returns a quoted version of the table name, used to construct SQL statements. + def quoted_table_name + @quoted_table_name ||= connection.quote_table_name(table_name) + end + + # Computes the table name, (re)sets it internally, and returns it. + def reset_table_name #:nodoc: + if active_record_super.abstract_class? + self.table_name = active_record_super.table_name || compute_table_name + elsif abstract_class? + self.table_name = active_record_super == Base ? nil : active_record_super.table_name + else + self.table_name = compute_table_name + end + end + + def full_table_name_prefix #:nodoc: + (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix + end + + # The name of the column containing the object's class when Single Table Inheritance is used + def inheritance_column + (@inheritance_column ||= nil) || active_record_super.inheritance_column + end + + # Sets the value of inheritance_column + def inheritance_column=(value) + @original_inheritance_column = inheritance_column + @inheritance_column = value.to_s + end + + def sequence_name + if base_class == self + @sequence_name ||= reset_sequence_name + else + (@sequence_name ||= nil) || base_class.sequence_name + end + end + + def reset_sequence_name #:nodoc: + self.sequence_name = connection.default_sequence_name(table_name, primary_key) + end + + # Sets the name of the sequence to use when generating ids to the given + # value, or (if the value is nil or false) to the value returned by the + # given block. This is required for Oracle and is useful for any + # database which relies on sequences for primary key generation. + # + # If a sequence name is not explicitly set when using Oracle or Firebird, + # it will default to the commonly used pattern of: #{table_name}_seq + # + # If a sequence name is not explicitly set when using PostgreSQL, it + # will discover the sequence corresponding to your primary key for you. + # + # class Project < ActiveRecord::Base + # self.sequence_name = "projectseq" # default would have been "project_seq" + # end + def sequence_name=(value) + @original_sequence_name = @sequence_name if defined?(@sequence_name) + @sequence_name = value.to_s + end + + # Indicates whether the table associated with this class exists + def table_exists? + connection.schema_cache.table_exists?(table_name) + end + + # 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| + col = col.dup + col.primary = (col.name == primary_key) + col + end + end + + # Returns a hash of column objects for the table associated with this class. + def columns_hash + @columns_hash ||= Hash[columns.map { |c| [c.name, c] }] + end + + # Returns a hash where the keys are column names and the values are + # default values when instantiating the AR object for this table. + def column_defaults + @column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }] + end + + # Returns an array of column names as strings. + def column_names + @column_names ||= columns.map { |column| column.name } + end + + # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", + # and columns used for single table inheritance have been removed. + def content_columns + @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } + end + + # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key + # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute + # is available. + def column_methods_hash #:nodoc: + @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr| + attr_name = attr.to_s + methods[attr.to_sym] = attr_name + methods["#{attr}=".to_sym] = attr_name + methods["#{attr}?".to_sym] = attr_name + methods["#{attr}_before_type_cast".to_sym] = attr_name + methods + end + end + + # Resets all the cached information about columns, which will cause them + # to be reloaded on the next request. + # + # The most common usage pattern for this method is probably in a migration, + # when just after creating a table you want to populate it with some default + # values, eg: + # + # class CreateJobLevels < ActiveRecord::Migration + # def up + # create_table :job_levels do |t| + # t.integer :id + # t.string :name + # + # t.timestamps + # end + # + # JobLevel.reset_column_information + # %w{assistant executive manager director}.each do |type| + # JobLevel.create(:name => type) + # end + # end + # + # def down + # drop_table :job_levels + # end + # end + def reset_column_information + connection.clear_cache! + undefine_attribute_methods + connection.schema_cache.clear_table_cache!(table_name) if table_exists? + + @column_names = @content_columns = @column_defaults = @columns = @columns_hash = nil + @dynamic_methods_hash = @inheritance_column = nil + @arel_engine = @relation = nil + end + + def clear_cache! # :nodoc: + connection.schema_cache.clear! + end + + private + + # Guesses the table name, but does not decorate it with prefix and suffix information. + def undecorated_table_name(class_name = base_class.name) + table_name = class_name.to_s.demodulize.underscore + table_name = table_name.pluralize if pluralize_table_names + table_name + end + + # Computes and returns a table name according to default conventions. + def compute_table_name + base = base_class + if self == base + # Nested classes are prefixed with singular parent table name. + if parent < ActiveRecord::Model && !parent.abstract_class? + contained = parent.table_name + contained = contained.singularize if parent.pluralize_table_names + contained += '_' + end + "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}" + else + # STI subclasses always use their superclass' table. + base.table_name + end + end + end + end +end diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb deleted file mode 100644 index 0313abe456..0000000000 --- a/activerecord/lib/active_record/named_scope.rb +++ /dev/null @@ -1,200 +0,0 @@ -require 'active_support/core_ext/array' -require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/kernel/singleton_class' -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/class/attribute' - -module ActiveRecord - # = Active Record Named \Scopes - module NamedScope - extend ActiveSupport::Concern - - module ClassMethods - # Returns an anonymous \scope. - # - # posts = Post.scoped - # posts.size # Fires "select count(*) from posts" and returns the count - # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects - # - # fruits = Fruit.scoped - # fruits = fruits.where(:color => 'red') if options[:red_only] - # fruits = fruits.limit(10) if limited? - # - # Anonymous \scopes tend to be useful when procedurally generating complex - # queries, where passing intermediate values (\scopes) around as first-class - # objects is convenient. - # - # You can define a \scope that applies to all finders using - # ActiveRecord::Base.default_scope. - def scoped(options = nil) - if options - scoped.apply_finder_options(options) - else - if current_scope - current_scope.clone - else - scope = relation.clone - scope.default_scoped = true - scope - end - end - end - - ## - # Collects attributes from scopes that should be applied when creating - # an AR instance for the particular class this is called on. - def scope_attributes # :nodoc: - if current_scope - current_scope.scope_for_create - else - scope = relation.clone - scope.default_scoped = true - scope.scope_for_create - end - end - - ## - # Are there default attributes associated with this scope? - def scope_attributes? # :nodoc: - current_scope || default_scopes.any? - end - - # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query, - # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>. - # - # class Shirt < ActiveRecord::Base - # scope :red, where(:color => 'red') - # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) - # end - # - # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, - # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. - # - # Note that this is simply 'syntactic sugar' for defining an actual class method: - # - # class Shirt < ActiveRecord::Base - # def self.red - # where(:color => 'red') - # end - # end - # - # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it - # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance, - # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>. - # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; - # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> - # all behave as if Shirt.red really was an Array. - # - # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce - # all shirts that are both red and dry clean only. - # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> - # returns the number of garments for which these criteria obtain. Similarly with - # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. - # - # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which - # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If, - # - # class Person < ActiveRecord::Base - # has_many :shirts - # end - # - # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean - # only shirts. - # - # Named \scopes can also be procedural: - # - # class Shirt < ActiveRecord::Base - # scope :colored, lambda { |color| where(:color => color) } - # end - # - # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. - # - # On Ruby 1.9 you can use the 'stabby lambda' syntax: - # - # scope :colored, ->(color) { where(:color => color) } - # - # Note that scopes defined with \scope will be evaluated when they are defined, rather than - # when they are used. For example, the following would be incorrect: - # - # class Post < ActiveRecord::Base - # scope :recent, where('published_at >= ?', Time.now - 1.week) - # end - # - # The example above would be 'frozen' to the <tt>Time.now</tt> value when the <tt>Post</tt> - # class was defined, and so the resultant SQL query would always be the same. The correct - # way to do this would be via a lambda, which will re-evaluate the scope each time - # it is called: - # - # class Post < ActiveRecord::Base - # scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) } - # end - # - # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: - # - # class Shirt < ActiveRecord::Base - # scope :red, where(:color => 'red') do - # def dom_id - # 'red_shirts' - # end - # end - # end - # - # Scopes can also be used while creating/building a record. - # - # class Article < ActiveRecord::Base - # scope :published, where(:published => true) - # end - # - # Article.published.new.published # => true - # Article.published.create.published # => true - # - # Class methods on your model are automatically available - # on scopes. Assuming the following setup: - # - # class Article < ActiveRecord::Base - # scope :published, where(:published => true) - # scope :featured, where(:featured => true) - # - # def self.latest_article - # order('published_at desc').first - # end - # - # def self.titles - # map(&:title) - # end - # - # end - # - # We are able to call the methods like this: - # - # Article.published.featured.latest_article - # Article.featured.titles - - def scope(name, scope_options = {}) - name = name.to_sym - valid_scope_name?(name) - extension = Module.new(&Proc.new) if block_given? - - scope_proc = lambda do |*args| - options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options - options = scoped.apply_finder_options(options) if options.is_a?(Hash) - - relation = scoped.merge(options) - - extension ? relation.extending(extension) : relation - end - - singleton_class.send(:redefine_method, name, &scope_proc) - end - - protected - - def valid_scope_name?(name) - if respond_to?(name, true) - logger.warn "Creating scope :#{name}. " \ - "Overwriting existing method #{self.name}.#{name}." - end - end - end - end -end diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 2dbebfcaf8..a8ee43b598 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -12,7 +12,7 @@ module ActiveRecord extend ActiveSupport::Concern included do - class_attribute :nested_attributes_options, :instance_writer => false + config_attribute :nested_attributes_options self.nested_attributes_options = {} end @@ -220,7 +220,7 @@ module ActiveRecord # validates_presence_of :member # end module ClassMethods - REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |_, value| value.blank? } } + REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } } # Defines an attributes writer for the specified association(s). If you # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you @@ -239,7 +239,8 @@ module ActiveRecord # is specified, a record will be built for all attribute hashes that # do not have a <tt>_destroy</tt> value that evaluates to true. # Passing <tt>:all_blank</tt> instead of a Proc will create a proc - # that will reject a record where all the attributes are blank. + # that will reject a record where all the attributes are blank excluding + # any value for _destroy. # [:limit] # Allows you to specify the maximum number of the associated records that # can be processed with the nested attributes. If the size of the diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index b5dadb929d..09ee2ba61d 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -1,6 +1,53 @@ +require 'active_support/concern' + module ActiveRecord # = Active Record Persistence module Persistence + extend ActiveSupport::Concern + + module ClassMethods + # Creates an object (or multiple objects) and saves it to the database, if validations pass. + # The resulting object is returned whether the object was saved successfully to the database or not. + # + # The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the + # attributes on the objects that are to be created. + # + # +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options + # in the +options+ parameter. + # + # ==== Examples + # # Create a single new object + # User.create(:first_name => 'Jamie') + # + # # Create a single new object using the :admin mass-assignment security role + # User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin) + # + # # Create a single new object bypassing mass-assignment security + # User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true) + # + # # Create an Array of new objects + # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) + # + # # Create a single object and pass it into a block to set other attributes. + # User.create(:first_name => 'Jamie') do |u| + # u.is_admin = false + # end + # + # # Creating an Array of new objects using a block, where the block is executed for each object: + # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u| + # u.is_admin = false + # end + def create(attributes = nil, options = {}, &block) + if attributes.is_a?(Array) + attributes.collect { |attr| create(attr, options, &block) } + else + object = new(attributes, options, &block) + object.save + object + end + end + end + # Returns true if this object hasn't been saved yet -- that is, a record # for the object doesn't exist in the data store yet; otherwise, returns false. def new_record? @@ -12,8 +59,8 @@ module ActiveRecord @destroyed end - # Returns if the record is persisted, i.e. it's not a new record and it was - # not destroyed. + # Returns true if the record is persisted, i.e. it's not a new record and it was + # not destroyed, otherwise returns false. def persisted? !(new_record? || destroyed?) end @@ -114,6 +161,7 @@ module ActiveRecord became.instance_variable_set("@attributes_cache", @attributes_cache) became.instance_variable_set("@new_record", new_record?) became.instance_variable_set("@destroyed", destroyed?) + became.instance_variable_set("@errors", errors) became.type = klass.name unless self.class.descends_from_active_record? became end @@ -161,7 +209,7 @@ module ActiveRecord # The following transaction covers any possible database side-effects of the # attributes assignment. For example, setting the IDs of a child collection. with_transaction_returning_status do - self.assign_attributes(attributes, options) + assign_attributes(attributes, options) save end end @@ -172,7 +220,7 @@ module ActiveRecord # The following transaction covers any possible database side-effects of the # attributes assignment. For example, setting the IDs of a child collection. with_transaction_returning_status do - self.assign_attributes(attributes, options) + assign_attributes(attributes, options) save! end end @@ -237,7 +285,7 @@ module ActiveRecord clear_association_cache IdentityMap.without do - fresh_object = self.class.unscoped { self.class.find(self.id, options) } + fresh_object = self.class.unscoped { self.class.find(id, options) } @attributes.update(fresh_object.instance_variable_get('@attributes')) end @@ -314,19 +362,11 @@ module ActiveRecord new_id = self.class.unscoped.insert attributes_values - self.id ||= new_id if self.class.primary_key? + self.id ||= new_id if self.class.primary_key IdentityMap.add(self) if IdentityMap.enabled? @new_record = false id end - - # Initializes the attributes array with keys matching the columns from the linked table and - # the values matching the corresponding default value of that column, so - # that a new instance, or one populated from a passed-in Hash, still has all the attributes - # that instances loaded from the database would. - def attributes_from_column_definition - self.class.column_defaults.dup - end end end diff --git a/activerecord/lib/active_record/query_cache.rb b/activerecord/lib/active_record/query_cache.rb index 10c0dc6f2a..466d148901 100644 --- a/activerecord/lib/active_record/query_cache.rb +++ b/activerecord/lib/active_record/query_cache.rb @@ -28,9 +28,10 @@ module ActiveRecord end class BodyProxy # :nodoc: - def initialize(original_cache_value, target) + def initialize(original_cache_value, target, connection_id) @original_cache_value = original_cache_value @target = target + @connection_id = connection_id end def method_missing(method_sym, *arguments, &block) @@ -48,6 +49,7 @@ module ActiveRecord def close @target.close if @target.respond_to?(:close) ensure + ActiveRecord::Base.connection_id = @connection_id ActiveRecord::Base.connection.clear_query_cache unless @original_cache_value ActiveRecord::Base.connection.disable_query_cache! @@ -60,7 +62,7 @@ module ActiveRecord ActiveRecord::Base.connection.enable_query_cache! status, headers, body = @app.call(env) - [status, headers, BodyProxy.new(old, body)] + [status, headers, BodyProxy.new(old, body, ActiveRecord::Base.connection_id)] rescue Exception => e ActiveRecord::Base.connection.clear_query_cache unless old diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb new file mode 100644 index 0000000000..09da9ad1d1 --- /dev/null +++ b/activerecord/lib/active_record/querying.rb @@ -0,0 +1,58 @@ +require 'active_support/core_ext/module/delegation' + +module ActiveRecord + module Querying + delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped + delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped + delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped + delegate :find_each, :find_in_batches, :to => :scoped + delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, + :where, :preload, :eager_load, :includes, :from, :lock, :readonly, + :having, :create_with, :uniq, :to => :scoped + delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :to => :scoped + + # Executes a custom SQL query against your database and returns all the results. The results will + # be returned as an array with columns requested encapsulated as attributes of the model you call + # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in + # a Product object with the attributes you specified in the SQL query. + # + # If you call a complicated SQL query which spans multiple tables the columns specified by the + # SELECT will be attributes of the model, whether or not they are columns of the corresponding + # table. + # + # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be + # no database agnostic conversions performed. This should be a last resort because using, for example, + # MySQL specific terms will lock you to using that particular database engine or require you to + # change your call if you switch engines. + # + # ==== Examples + # # A simple SQL query spanning multiple tables + # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" + # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] + # + # # You can use the same string replacement techniques as you can with ActiveRecord#find + # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] + # > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...] + def find_by_sql(sql, binds = []) + logging_query_plan do + connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) } + end + end + + # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. + # The use of this method should be restricted to complicated SQL queries that can't be executed + # using the ActiveRecord::Calculations class methods. Look into those before using this. + # + # ==== Parameters + # + # * +sql+ - An SQL statement which should return a count query from the database, see the example below. + # + # ==== Examples + # + # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" + def count_by_sql(sql) + sql = sanitize_conditions(sql) + connection.select_value(sql, "#{name} Count").to_i + end + end +end diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index 47133e77e8..165d0750dd 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -22,6 +22,13 @@ module ActiveRecord config.app_middleware.insert_after "::ActionDispatch::Callbacks", "ActiveRecord::ConnectionAdapters::ConnectionManagement" + config.action_dispatch.rescue_responses.merge!( + 'ActiveRecord::RecordNotFound' => :not_found, + 'ActiveRecord::StaleObjectError' => :conflict, + 'ActiveRecord::RecordInvalid' => :unprocessable_entity, + 'ActiveRecord::RecordNotSaved' => :unprocessable_entity + ) + rake_tasks do load "active_record/railties/databases.rake" end @@ -78,18 +85,30 @@ module ActiveRecord end end - initializer "active_record.set_dispatch_hooks", :before => :set_clear_dependencies_hook do |app| - ActiveSupport.on_load(:active_record) do - ActionDispatch::Reloader.to_cleanup do - ActiveRecord::Base.clear_reloadable_connections! - ActiveRecord::Base.clear_cache! + initializer "active_record.set_reloader_hooks" do |app| + hook = lambda do + ActiveRecord::Base.clear_reloadable_connections! + ActiveRecord::Base.clear_cache! + end + + if app.config.reload_classes_only_on_change + ActiveSupport.on_load(:active_record) do + ActionDispatch::Reloader.to_prepare(&hook) + end + else + ActiveSupport.on_load(:active_record) do + ActionDispatch::Reloader.to_cleanup(&hook) end end end + initializer "active_record.add_watchable_files" do |app| + config.watchable_files.concat ["#{app.root}/db/schema.rb", "#{app.root}/db/structure.sql"] + end + config.after_initialize do ActiveSupport.on_load(:active_record) do - instantiate_observers + ActiveRecord::Base.instantiate_observers ActionDispatch::Reloader.to_prepare do ActiveRecord::Base.instantiate_observers diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index f4a813d704..180424641a 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -1,8 +1,8 @@ require 'active_support/core_ext/object/inclusion' +require 'active_record' db_namespace = namespace :db do task :load_config => :rails_env do - require 'active_record' ActiveRecord::Base.configurations = Rails.application.config.database_configuration ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a @@ -37,11 +37,8 @@ db_namespace = namespace :db do desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)' task :create => :load_config do - # Make the test database at the same time as the development one, if it exists - if Rails.env.development? && ActiveRecord::Base.configurations['test'] - create_database(ActiveRecord::Base.configurations['test']) - end - create_database(ActiveRecord::Base.configurations[Rails.env]) + configs_for_environment.each { |config| create_database(config) } + ActiveRecord::Base.establish_connection(configs_for_environment.first) end def mysql_creation_options(config) @@ -115,8 +112,7 @@ db_namespace = namespace :db do end end else - # Bug with 1.9.2 Calling return within begin still executes else - $stderr.puts "#{config['database']} already exists" unless config['adapter'] =~ /sqlite/ + $stderr.puts "#{config['database']} already exists" end end @@ -138,12 +134,7 @@ db_namespace = namespace :db do desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)' task :drop => :load_config do - config = ActiveRecord::Base.configurations[Rails.env || 'development'] - begin - drop_database(config) - rescue Exception => e - $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}" - end + configs_for_environment.each { |config| drop_database_and_rescue(config) } end def local_database?(config, &block) @@ -158,8 +149,19 @@ db_namespace = namespace :db do desc "Migrate the database (options: VERSION=x, VERBOSE=false)." task :migrate => [:environment, :load_config] do ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true - ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) - db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) do |migration| + ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) + end + db_namespace['_dump'].invoke + end + + task :_dump do + case ActiveRecord::Base.schema_format + when :ruby then db_namespace["schema:dump"].invoke + when :sql then db_namespace["structure:dump"].invoke + else + raise "unknown schema format #{ActiveRecord::Base.schema_format}" + end end namespace :migrate do @@ -182,7 +184,7 @@ db_namespace = namespace :db do version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil raise 'VERSION is required' unless version ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end # desc 'Runs the "down" for a given migration VERSION.' @@ -190,7 +192,7 @@ db_namespace = namespace :db do version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil raise 'VERSION is required' unless version ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end desc 'Display status of migrations' @@ -230,18 +232,21 @@ db_namespace = namespace :db do task :rollback => [:environment, :load_config] do step = ENV['STEP'] ? ENV['STEP'].to_i : 1 ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).' task :forward => [:environment, :load_config] do step = ENV['STEP'] ? ENV['STEP'].to_i : 1 ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step) - db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby + db_namespace['_dump'].invoke end # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.' - task :reset => [ 'db:drop', 'db:setup' ] + task :reset => :environment do + db_namespace["drop"].invoke + db_namespace["setup"].invoke + end # desc "Retrieves the charset for the current environment's database" task :charset => :environment do @@ -280,24 +285,23 @@ db_namespace = namespace :db do # desc "Raises an error if there are pending migrations" task :abort_if_pending_migrations => :environment do - if defined? ActiveRecord - pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations + pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations - if pending_migrations.any? - puts "You have #{pending_migrations.size} pending migrations:" - pending_migrations.each do |pending_migration| - puts ' %4d %s' % [pending_migration.version, pending_migration.name] - end - abort %{Run "rake db:migrate" to update your database then try again.} + if pending_migrations.any? + puts "You have #{pending_migrations.size} pending migrations:" + pending_migrations.each do |pending_migration| + puts ' %4d %s' % [pending_migration.version, pending_migration.name] end + abort %{Run `rake db:migrate` to update your database then try again.} end end desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)' - task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ] + task :setup => ['db:schema:load_if_ruby', 'db:structure:load_if_sql', :seed] desc 'Load the seed data from db/seeds.rb' - task :seed => 'db:abort_if_pending_migrations' do + task :seed do + db_namespace['abort_if_pending_migrations'].invoke Rails.application.load_seed end @@ -357,93 +361,125 @@ db_namespace = namespace :db do if File.exists?(file) load(file) else - abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded} + abort %{#{file} doesn't exist yet. Run `rake db:migrate` to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded} end end + + task :load_if_ruby => 'db:create' do + db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby + end end namespace :structure do - desc 'Dump the database structure to an SQL file' + desc 'Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql' task :dump => :environment do abcs = ActiveRecord::Base.configurations + filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql") case abcs[Rails.env]['adapter'] when /mysql/, 'oci', 'oracle' ActiveRecord::Base.establish_connection(abcs[Rails.env]) - File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump } + File.open(filename, "w:utf-8") { |f| f << ActiveRecord::Base.connection.structure_dump } when /postgresql/ - ENV['PGHOST'] = abcs[Rails.env]['host'] if abcs[Rails.env]['host'] - ENV['PGPORT'] = abcs[Rails.env]["port"].to_s if abcs[Rails.env]['port'] - ENV['PGPASSWORD'] = abcs[Rails.env]['password'].to_s if abcs[Rails.env]['password'] + set_psql_env(abcs[Rails.env]) search_path = abcs[Rails.env]['schema_search_path'] unless search_path.blank? search_path = search_path.split(",").map{|search_path_part| "--schema=#{search_path_part.strip}" }.join(" ") end - `pg_dump -i -U "#{abcs[Rails.env]['username']}" -s -x -O -f db/#{Rails.env}_structure.sql #{search_path} #{abcs[Rails.env]['database']}` + `pg_dump -i -s -x -O -f #{filename} #{search_path} #{abcs[Rails.env]['database']}` raise 'Error dumping database' if $?.exitstatus == 1 when /sqlite/ - dbfile = abcs[Rails.env]['database'] || abcs[Rails.env]['dbfile'] - `sqlite3 #{dbfile} .schema > db/#{Rails.env}_structure.sql` + dbfile = abcs[Rails.env]['database'] + `sqlite3 #{dbfile} .schema > #{filename}` when 'sqlserver' - `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f db\\#{Rails.env}_structure.sql -A -U` + `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f #{filename} -A -U` when "firebird" set_firebird_env(abcs[Rails.env]) db_string = firebird_db_string(abcs[Rails.env]) - sh "isql -a #{db_string} > #{Rails.root}/db/#{Rails.env}_structure.sql" + sh "isql -a #{db_string} > #{filename}" else raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'" end if ActiveRecord::Base.connection.supports_migrations? - File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } + File.open(filename, "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } end end - end - - namespace :test do - # desc "Recreate the test database from the current schema.rb" - task :load => 'db:test:purge' do - ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']) - ActiveRecord::Schema.verbose = false - db_namespace['schema:load'].invoke - end - # desc "Recreate the test database from the current environment's database schema" - task :clone => %w(db:schema:dump db:test:load) + # desc "Recreate the databases from the structure.sql file" + task :load => [:environment, :load_config] do + env = ENV['RAILS_ENV'] || 'test' - # desc "Recreate the test databases from the development structure" - task :clone_structure => [ 'db:structure:dump', 'db:test:purge' ] do abcs = ActiveRecord::Base.configurations - case abcs['test']['adapter'] + filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql") + case abcs[env]['adapter'] when /mysql/ - ActiveRecord::Base.establish_connection(:test) + ActiveRecord::Base.establish_connection(abcs[env]) ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0') - IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split("\n\n").each do |table| + IO.read(filename).split("\n\n").each do |table| ActiveRecord::Base.connection.execute(table) end when /postgresql/ - ENV['PGHOST'] = abcs['test']['host'] if abcs['test']['host'] - ENV['PGPORT'] = abcs['test']['port'].to_s if abcs['test']['port'] - ENV['PGPASSWORD'] = abcs['test']['password'].to_s if abcs['test']['password'] - `psql -U "#{abcs['test']['username']}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs['test']['database']} #{abcs['test']['template']}` + set_psql_env(abcs[env]) + `psql -f "#{filename}" #{abcs[env]['database']} #{abcs[env]['template']}` when /sqlite/ - dbfile = abcs['test']['database'] || abcs['test']['dbfile'] - `sqlite3 #{dbfile} < #{Rails.root}/db/#{Rails.env}_structure.sql` + dbfile = abcs[env]['database'] + `sqlite3 #{dbfile} < "#{filename}"` when 'sqlserver' - `sqlcmd -S #{abcs['test']['host']} -d #{abcs['test']['database']} -U #{abcs['test']['username']} -P #{abcs['test']['password']} -i db\\#{Rails.env}_structure.sql` + `sqlcmd -S #{abcs[env]['host']} -d #{abcs[env]['database']} -U #{abcs[env]['username']} -P #{abcs[env]['password']} -i #{filename}` when 'oci', 'oracle' - ActiveRecord::Base.establish_connection(:test) - IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split(";\n\n").each do |ddl| + ActiveRecord::Base.establish_connection(abcs[env]) + IO.read(filename).split(";\n\n").each do |ddl| ActiveRecord::Base.connection.execute(ddl) end when 'firebird' - set_firebird_env(abcs['test']) - db_string = firebird_db_string(abcs['test']) - sh "isql -i #{Rails.root}/db/#{Rails.env}_structure.sql #{db_string}" + set_firebird_env(abcs[env]) + db_string = firebird_db_string(abcs[env]) + sh "isql -i #{filename} #{db_string}" else - raise "Task not supported by '#{abcs['test']['adapter']}'" + raise "Task not supported by '#{abcs[env]['adapter']}'" end end + task :load_if_sql => 'db:create' do + db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql + end + end + + namespace :test do + + # desc "Recreate the test database from the current schema" + task :load => 'db:test:purge' do + case ActiveRecord::Base.schema_format + when :ruby + db_namespace["test:load_schema"].invoke + when :sql + db_namespace["test:load_structure"].invoke + end + end + + # desc "Recreate the test database from an existent structure.sql file" + task :load_structure => 'db:test:purge' do + begin + old_env, ENV['RAILS_ENV'] = ENV['RAILS_ENV'], 'test' + db_namespace["structure:load"].invoke + ensure + ENV['RAILS_ENV'] = old_env + end + end + + # desc "Recreate the test database from an existent schema.rb file" + task :load_schema => 'db:test:purge' do + ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']) + ActiveRecord::Schema.verbose = false + db_namespace["schema:load"].invoke + end + + # desc "Recreate the test database from a fresh schema.rb file" + task :clone => %w(db:schema:dump db:test:load_schema) + + # desc "Recreate the test database from a fresh structure.sql file" + task :clone_structure => [ "db:structure:dump", "db:test:load_structure" ] + # desc "Empty the test database" task :purge => :environment do abcs = ActiveRecord::Base.configurations @@ -456,7 +492,7 @@ db_namespace = namespace :db do drop_database(abcs['test']) create_database(abcs['test']) when /sqlite/ - dbfile = abcs['test']['database'] || abcs['test']['dbfile'] + dbfile = abcs['test']['database'] File.delete(dbfile) if File.exist?(dbfile) when 'sqlserver' test = abcs.deep_dup['test'] @@ -479,7 +515,7 @@ db_namespace = namespace :db do # desc 'Check for pending migrations and load the test schema' task :prepare => 'db:abort_if_pending_migrations' do - if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank? + unless ActiveRecord::Base.configurations.blank? db_namespace[{ :sql => 'test:clone_structure', :ruby => 'test:load' }[ActiveRecord::Base.schema_format]].invoke end end @@ -548,6 +584,20 @@ def drop_database(config) end end +def drop_database_and_rescue(config) + begin + drop_database(config) + rescue Exception => e + $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}" + end +end + +def configs_for_environment + environments = [Rails.env] + environments << 'test' if Rails.env.development? + ActiveRecord::Base.configurations.values_at(*environments).compact.reject { |config| config['database'].blank? } +end + def session_table_name ActiveRecord::SessionStore::Session.table_name end @@ -560,3 +610,10 @@ end def firebird_db_string(config) FireRuby::Database.db_string_for(config.symbolize_keys) end + +def set_psql_env(config) + ENV['PGHOST'] = config['host'] if config['host'] + ENV['PGPORT'] = config['port'].to_s if config['port'] + ENV['PGPASSWORD'] = config['password'].to_s if config['password'] + ENV['PGUSER'] = config['username'].to_s if config['username'] +end diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb new file mode 100644 index 0000000000..836b15e2ce --- /dev/null +++ b/activerecord/lib/active_record/readonly_attributes.rb @@ -0,0 +1,26 @@ +require 'active_support/concern' +require 'active_support/core_ext/class/attribute' + +module ActiveRecord + module ReadonlyAttributes + extend ActiveSupport::Concern + + included do + config_attribute :_attr_readonly + self._attr_readonly = [] + end + + module ClassMethods + # Attributes listed as readonly will be used to create a new record but update operations will + # ignore these fields. + def attr_readonly(*attributes) + self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || []) + end + + # Returns an array of all the attributes that have been specified as readonly. + def readonly_attributes + self._attr_readonly + end + end + end +end diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 120ff0cac6..60b73e9fe5 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -7,7 +7,8 @@ module ActiveRecord extend ActiveSupport::Concern included do - class_attribute :reflections + extend ActiveModel::Configuration + config_attribute :reflections self.reflections = {} end @@ -124,7 +125,7 @@ module ActiveRecord # <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt> # <tt>has_many :clients</tt> returns <tt>'Client'</tt> def class_name - @class_name ||= options[:class_name] || derive_class_name + @class_name ||= (options[:class_name] || derive_class_name).to_s end # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute, @@ -213,11 +214,11 @@ module ActiveRecord # klass option is necessary to support loading polymorphic associations def association_primary_key(klass = nil) - options[:primary_key] || (klass || self.klass).primary_key + options[:primary_key] || primary_key(klass || self.klass) end def active_record_primary_key - @active_record_primary_key ||= options[:primary_key] || active_record.primary_key + @active_record_primary_key ||= options[:primary_key] || primary_key(active_record) end def counter_cache_column @@ -262,6 +263,10 @@ module ActiveRecord [self] end + def nested? + false + end + # An array of arrays of conditions. Each item in the outside array corresponds to a reflection # in the #chain. The inside arrays are simply conditions (and each condition may itself be # a hash, array, arel predicate, etc...) @@ -357,6 +362,10 @@ module ActiveRecord active_record.name.foreign_key end end + + def primary_key(klass) + klass.primary_key || raise(UnknownPrimaryKey.new(klass)) + end end # Holds all the meta-data about a :through association as it was specified @@ -429,7 +438,7 @@ module ActiveRecord # of relevant reflections, plus any :source_type or polymorphic :as constraints. def conditions @conditions ||= begin - conditions = source_reflection.conditions + conditions = source_reflection.conditions.map { |c| c.dup } # Add to it the conditions from this reflection if necessary. conditions.first << options[:conditions] if options[:conditions] @@ -453,7 +462,7 @@ module ActiveRecord source_reflection.source_macro end - # A through association is nested iff there would be more than one join table + # A through association is nested if there would be more than one join table def nested? chain.length > 2 || through_reflection.macro == :has_and_belongs_to_many end @@ -461,7 +470,7 @@ module ActiveRecord # We want to use the klass from this reflection, rather than just delegate straight to # the source_reflection, because the source_reflection may be polymorphic. We still # need to respect the source_reflection's :primary_key option, though. - def association_primary_key(klass = self.klass) + def association_primary_key(klass = nil) # Get the "actual" source reflection if the immediate source reflection has a # source reflection itself source_reflection = self.source_reflection @@ -469,7 +478,7 @@ module ActiveRecord source_reflection = source_reflection.source_reflection end - source_reflection.options[:primary_key] || klass.primary_key + source_reflection.options[:primary_key] || primary_key(klass || self.klass) end # Gets an array of possible <tt>:through</tt> source reflection names: diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index bf61d79a2c..6f2248fa21 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -1,5 +1,6 @@ +# -*- coding: utf-8 -*- require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/module/delegation' +require 'active_support/deprecation' module ActiveRecord # = Active Record Relation @@ -7,13 +8,9 @@ module ActiveRecord JoinOperation = Struct.new(:relation, :join_class, :on) ASSOCIATION_METHODS = [:includes, :eager_load, :preload] MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind] - SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order] + SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order, :uniq] - include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches - - # These are explicitly delegated to improve performance (avoids method_missing) - delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a - delegate :table_name, :quoted_table_name, :primary_key, :primary_key?, :quoted_primary_key, :connection, :column_hash,:to => :klass + include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation attr_reader :table, :klass, :loaded attr_accessor :extensions, :default_scoped @@ -36,7 +33,7 @@ module ActiveRecord def insert(values) primary_key_value = nil - if primary_key? && Hash === values + if primary_key && Hash === values primary_key_value = values[values.keys.find { |k| k.name == primary_key }] @@ -70,7 +67,7 @@ module ActiveRecord conn.insert( im, 'SQL', - primary_key? && primary_key, + primary_key, primary_key_value, nil, binds) @@ -136,14 +133,35 @@ module ActiveRecord first || new(attributes, options, &block) end - def respond_to?(method, include_private = false) - arel.respond_to?(method, include_private) || - Array.method_defined?(method) || - @klass.respond_to?(method, include_private) || - super + # Runs EXPLAIN on the query or queries triggered by this relation and + # returns the result as a string. The string is formatted imitating the + # ones printed by the database shell. + # + # Note that this method actually runs the queries, since the results of some + # are needed by the next ones when eager loading is going on. + # + # Please see further details in the + # {Active Record Query Interface guide}[http://edgeguides.rubyonrails.org/active_record_querying.html#running-explain]. + def explain + _, queries = collecting_queries_for_explain { exec_queries } + exec_explain(queries) end def to_a + # We monitor here the entire execution rather than individual SELECTs + # because from the point of view of the user fetching the records of a + # relation is a single unit of work. You want to know if this call takes + # too long, not if the individual queries take too long. + # + # It could be the case that none of the queries involved surpass the + # threshold, and at the same time the sum of them all does. The user + # should get a query plan logged in that case. + logging_query_plan do + exec_queries + end + end + + def exec_queries return @records if loaded? default_scoped = with_default_scope @@ -174,6 +192,7 @@ module ActiveRecord @loaded = true @records end + private :exec_queries def as_json(options = nil) #:nodoc: to_a.as_json(options) @@ -219,7 +238,7 @@ module ActiveRecord # Please check unscoped if you want to remove all previous scopes (including # the default_scope) during the execution of a block. def scoping - @klass.send(:with_scope, self, :overwrite) { yield } + @klass.with_scope(self, :overwrite) { yield } end # Updates all records with details given if they match a set of conditions supplied, limits and order can @@ -337,7 +356,7 @@ module ActiveRecord end end - # Destroy an object (or multiple objects) that has the given id, the object is instantiated first, + # Destroy an object (or multiple objects) that has the given id. The object is instantiated first, # therefore all callbacks and filters are fired off before the object is deleted. This method is # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run. # @@ -487,20 +506,6 @@ module ActiveRecord end end - protected - - def method_missing(method, *args, &block) - if Array.method_defined?(method) - to_a.send(method, *args, &block) - elsif @klass.respond_to?(method) - scoping { @klass.send(method, *args, &block) } - elsif arel.respond_to?(method) - arel.send(method, *args, &block) - else - super - end - end - private def references_eager_loaded_tables? @@ -517,7 +522,18 @@ module ActiveRecord # always convert table names to downcase as in Oracle quoted table names are in uppercase joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq - (tables_in_string(to_sql) - joined_tables).any? + referenced_tables = (tables_in_string(to_sql) - joined_tables) + if referenced_tables.any? + ActiveSupport::Deprecation.warn( + "Your query appears to reference tables (#{referenced_tables.join(', ')}) that are not " \ + "explicitly joined. This implicit joining is deprecated, so you must explicitly " \ + "reference the tables. For example, instead of Author.includes(:posts).where(\"posts.name = 'foo'\"), " \ + "you should write Author.eager_load(:posts).where(\"posts.name = 'foo'\")." + ) + true + else + false + end end def tables_in_string(string) @@ -526,6 +542,5 @@ module ActiveRecord # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_'] end - end end diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index af86771d2d..bf9b4bf1c9 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -166,6 +166,22 @@ module ActiveRecord 0 end + # This method is designed to perform select by a single column as direct SQL query + # Returns <tt>Array</tt> with values of the specified column name + # The values has same data type as column. + # + # Examples: + # + # Person.pluck(:id) # SELECT people.id FROM people + # Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people + # Person.where(:confirmed => true).limit(5).pluck(:id) + # + def pluck(column_name) + klass.connection.select_all(select(column_name).arel).map! do |attributes| + klass.type_cast_attribute(attributes.keys.first, klass.initialize_attributes(attributes)) + end + end + private def perform_calculation(operation, column_name, options = {}) diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb new file mode 100644 index 0000000000..f5fdf437bf --- /dev/null +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -0,0 +1,49 @@ +require 'active_support/core_ext/module/delegation' + +module ActiveRecord + module Delegation + # Set up common delegations for performance (avoids method_missing) + delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :to => :to_a + delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, + :connection, :columns_hash, :auto_explain_threshold_in_seconds, :to => :klass + + def self.delegate_to_scoped_klass(method) + if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/ + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args, &block) + scoping { @klass.#{method}(*args, &block) } + end + RUBY + else + module_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args, &block) + scoping { @klass.send(#{method.inspect}, *args, &block) } + end + RUBY + end + end + + def respond_to?(method, include_private = false) + super || Array.method_defined?(method) || + @klass.respond_to?(method, include_private) || + arel.respond_to?(method, include_private) + end + + protected + + def method_missing(method, *args, &block) + if Array.method_defined?(method) + ::ActiveRecord::Delegation.delegate method, :to => :to_a + to_a.send(method, *args, &block) + elsif @klass.respond_to?(method) + ::ActiveRecord::Delegation.delegate_to_scoped_klass(method) + scoping { @klass.send(method, *args, &block) } + elsif arel.respond_to?(method) + ::ActiveRecord::Delegation.delegate method, :to => :arel + arel.send(method, *args, &block) + else + super + end + end + end +end
\ No newline at end of file diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 7eeb3dde70..e58c726e09 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -187,11 +187,11 @@ module ActiveRecord def exists?(id = false) return false if id.nil? - id = id.id if ActiveRecord::Base === id + id = id.id if ActiveRecord::Model === id join_dependency = construct_join_dependency_for_association_find relation = construct_relation_for_association_find(join_dependency) - relation = relation.except(:select).select("1").limit(1) + relation = relation.except(:select, :order).select("1").limit(1) case id when Array, Hash @@ -249,7 +249,7 @@ module ActiveRecord end def construct_limited_ids_condition(relation) - orders = relation.order_values.map { |val| val.presence }.compact + orders = (relation.reorder_value || relation.order_values).map { |val| val.presence }.compact values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders) relation = relation.dup diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 7e8ddd1b5d..88081edae2 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -15,42 +15,49 @@ module ActiveRecord table = Arel::Table.new(table_name, engine) end - attribute = table[column.to_sym] + build(table[column.to_sym], value) + end + end + predicates.flatten + end + + private + def self.build(attribute, value) + case value + when ActiveRecord::Relation + value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty? + attribute.in(value.arel.ast) + when Array, ActiveRecord::Associations::CollectionProxy + values = value.to_a.map {|x| x.is_a?(ActiveRecord::Model) ? x.id : x} + ranges, values = values.partition {|v| v.is_a?(Range) || v.is_a?(Arel::Relation)} - case value - when ActiveRecord::Relation - value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty? - attribute.in(value.arel.ast) - when Array, ActiveRecord::Associations::CollectionProxy - values = value.to_a.map { |x| - x.is_a?(ActiveRecord::Base) ? x.id : x - } + array_predicates = ranges.map {|range| attribute.in(range)} - if values.include?(nil) - values = values.compact - if values.empty? - attribute.eq nil - else - attribute.in(values.compact).or attribute.eq(nil) - end + if values.include?(nil) + values = values.compact + case values.length + when 0 + array_predicates << attribute.eq(nil) + when 1 + array_predicates << attribute.eq(values.first).or(attribute.eq(nil)) else - attribute.in(values) + array_predicates << attribute.in(values).or(attribute.eq(nil)) end - - when Range, Arel::Relation - attribute.in(value) - when ActiveRecord::Base - attribute.eq(value.id) - when Class - # FIXME: I think we need to deprecate this behavior - attribute.eq(value.name) else - attribute.eq(value) + array_predicates << attribute.in(values) end + + array_predicates.inject {|composite, predicate| composite.or(predicate)} + when Range, Arel::Relation + attribute.in(value) + when ActiveRecord::Model + attribute.eq(value.id) + when Class + # FIXME: I think we need to deprecate this behavior + attribute.eq(value.name) + else + attribute.eq(value) end end - - predicates.flatten - end end end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 670ba0987d..c281bead0d 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -9,7 +9,8 @@ module ActiveRecord :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values, :bind_values, :limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, - :from_value, :reorder_value, :reverse_order_value + :from_value, :reorder_value, :reverse_order_value, + :uniq_value def includes(*args) args.reject! {|a| a.blank? } @@ -38,7 +39,7 @@ module ActiveRecord end # Works in two unique ways. - # + # # First: takes a block so it can be used just like Array#select. # # Model.scoped.select { |m| m.field == value } @@ -176,9 +177,25 @@ module ActiveRecord relation end + # Specifies whether the records should be unique or not. For example: + # + # User.select(:name) + # # => Might return two records with the same name + # + # User.select(:name).uniq + # # => Returns 1 record per unique name + # + # User.select(:name).uniq.uniq(false) + # # => You can also remove the uniqueness + def uniq(value = true) + relation = clone + relation.uniq_value = value + relation + end + # Used to extend a scope with additional methods, either through - # a module or through a block provided. - # + # a module or through a block provided. + # # The object returned is a relation, which can be further extended. # # === Using a module @@ -200,7 +217,7 @@ module ActiveRecord # # scope = Model.scoped.extending do # def page(number) - # # pagination code goes here + # # pagination code goes here # end # end # scope.page(params[:page]) @@ -209,7 +226,7 @@ module ActiveRecord # # scope = Model.scoped.extending(Pagination) do # def per_page(number) - # # pagination code goes here + # # pagination code goes here # end # end def extending(*modules) @@ -252,6 +269,7 @@ module ActiveRecord build_select(arel, @select_values.uniq) + arel.distinct(@uniq_value) arel.from(@from_value) if @from_value arel.lock(@lock_value) if @lock_value diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb index ba882beca9..a5194beae5 100644 --- a/activerecord/lib/active_record/relation/spawn_methods.rb +++ b/activerecord/lib/active_record/relation/spawn_methods.rb @@ -113,7 +113,7 @@ module ActiveRecord result end - VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend, + VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend, :eager_load, :order, :select, :readonly, :group, :having, :from, :lock ] def apply_finder_options(options) @@ -124,7 +124,7 @@ module ActiveRecord finders = options.dup finders.delete_if { |key, value| value.nil? && key != :limit } - ([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly] & finders.keys).each do |finder| + ([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly, :eager_load] & finders.keys).each do |finder| relation = relation.send(finder, finders[finder]) end diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb new file mode 100644 index 0000000000..2d7d83d160 --- /dev/null +++ b/activerecord/lib/active_record/sanitization.rb @@ -0,0 +1,194 @@ +require 'active_support/concern' + +module ActiveRecord + module Sanitization + extend ActiveSupport::Concern + + module ClassMethods + def quote_value(value, column = nil) #:nodoc: + connection.quote(value,column) + end + + # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. + def sanitize(object) #:nodoc: + connection.quote(object) + end + + protected + + # Accepts an array, hash, or string of SQL conditions and sanitizes + # them into a valid SQL fragment for a WHERE clause. + # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" + # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" + # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'" + def sanitize_sql_for_conditions(condition, table_name = self.table_name) + return nil if condition.blank? + + case condition + when Array; sanitize_sql_array(condition) + when Hash; sanitize_sql_hash_for_conditions(condition, table_name) + else condition + end + end + alias_method :sanitize_sql, :sanitize_sql_for_conditions + + # Accepts an array, hash, or string of SQL conditions and sanitizes + # them into a valid SQL fragment for a SET clause. + # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'" + def sanitize_sql_for_assignment(assignments) + case assignments + when Array; sanitize_sql_array(assignments) + when Hash; sanitize_sql_hash_for_assignment(assignments) + else assignments + end + end + + # Accepts a hash of SQL conditions and replaces those attributes + # that correspond to a +composed_of+ relationship with their expanded + # aggregate attribute values. + # Given: + # class Person < ActiveRecord::Base + # composed_of :address, :class_name => "Address", + # :mapping => [%w(address_street street), %w(address_city city)] + # end + # Then: + # { :address => Address.new("813 abc st.", "chicago") } + # # => { :address_street => "813 abc st.", :address_city => "chicago" } + def expand_hash_conditions_for_aggregates(attrs) + expanded_attrs = {} + attrs.each do |attr, value| + unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil? + mapping = aggregate_mapping(aggregation) + mapping.each do |field_attr, aggregate_attr| + if mapping.size == 1 && !value.respond_to?(aggregate_attr) + expanded_attrs[field_attr] = value + else + expanded_attrs[field_attr] = value.send(aggregate_attr) + end + end + else + expanded_attrs[attr] = value + end + end + expanded_attrs + end + + # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause. + # { :name => "foo'bar", :group_id => 4 } + # # => "name='foo''bar' and group_id= 4" + # { :status => nil, :group_id => [1,2,3] } + # # => "status IS NULL and group_id IN (1,2,3)" + # { :age => 13..18 } + # # => "age BETWEEN 13 AND 18" + # { 'other_records.id' => 7 } + # # => "`other_records`.`id` = 7" + # { :other_records => { :id => 7 } } + # # => "`other_records`.`id` = 7" + # 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'" + def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) + attrs = expand_hash_conditions_for_aggregates(attrs) + + table = Arel::Table.new(table_name).alias(default_table_name) + PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b| + connection.visitor.accept b + }.join(' AND ') + end + alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions + + # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. + # { :status => nil, :group_id => 1 } + # # => "status = NULL , group_id = 1" + def sanitize_sql_hash_for_assignment(attrs) + attrs.map do |attr, value| + "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}" + end.join(', ') + end + + # Accepts an array of conditions. The array has each value + # sanitized and interpolated into the SQL statement. + # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" + def sanitize_sql_array(ary) + statement, *values = ary + if values.first.is_a?(Hash) && statement =~ /:\w+/ + replace_named_bind_variables(statement, values.first) + elsif statement.include?('?') + replace_bind_variables(statement, values) + elsif statement.blank? + statement + else + statement % values.collect { |value| connection.quote_string(value.to_s) } + end + end + + alias_method :sanitize_conditions, :sanitize_sql + + def replace_bind_variables(statement, values) #:nodoc: + raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) + bound = values.dup + c = connection + statement.gsub('?') { quote_bound_value(bound.shift, c) } + end + + def replace_named_bind_variables(statement, bind_vars) #:nodoc: + statement.gsub(/(:?):([a-zA-Z]\w*)/) do + if $1 == ':' # skip postgresql casts + $& # return the whole match + elsif bind_vars.include?(match = $2.to_sym) + quote_bound_value(bind_vars[match]) + else + raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" + end + end + end + + def expand_range_bind_variables(bind_vars) #:nodoc: + expanded = [] + + bind_vars.each do |var| + next if var.is_a?(Hash) + + if var.is_a?(Range) + expanded << var.first + expanded << var.last + else + expanded << var + end + end + + expanded + end + + def quote_bound_value(value, c = connection) #:nodoc: + if value.respond_to?(:map) && !value.acts_like?(:string) + if value.respond_to?(:empty?) && value.empty? + c.quote(nil) + else + value.map { |v| c.quote(v) }.join(',') + end + else + c.quote(value) + end + end + + def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc: + unless expected == provided + raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" + end + end + end + + # TODO: Deprecate this + def quoted_id #:nodoc: + quote_value(id, column_for_attribute(self.class.primary_key)) + end + + private + + # Quote strings appropriately for SQL statements. + def quote_value(value, column = nil) + self.class.connection.quote(value, column) + end + end +end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 6fe305f843..cdde5cf3b9 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -190,6 +190,9 @@ HEADER index_lengths = (index.lengths || []).compact statement_parts << (':length => ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty? + index_orders = (index.orders || {}) + statement_parts << (':order => ' + index.orders.inspect) unless index_orders.empty? + ' ' + statement_parts.join(', ') end diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb new file mode 100644 index 0000000000..a8f5e96190 --- /dev/null +++ b/activerecord/lib/active_record/scoping.rb @@ -0,0 +1,152 @@ +require 'active_support/concern' + +module ActiveRecord + module Scoping + extend ActiveSupport::Concern + + included do + include Default + include Named + end + + module ClassMethods + # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be + # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while + # <tt>:create</tt> parameters are an attributes hash. + # + # class Article < ActiveRecord::Base + # def self.create_with_scope + # with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do + # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 + # a = create(1) + # a.blog_id # => 1 + # end + # end + # end + # + # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of + # <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged. + # + # <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing + # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the + # array of strings format for your joins. + # + # class Article < ActiveRecord::Base + # def self.find_with_scope + # with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do + # with_scope(:find => limit(10)) do + # all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 + # end + # with_scope(:find => where(:author_id => 3)) do + # all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 + # end + # end + # end + # end + # + # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method. + # + # class Article < ActiveRecord::Base + # def self.find_with_exclusive_scope + # with_scope(:find => where(:blog_id => 1).limit(1)) do + # with_exclusive_scope(:find => limit(10)) do + # all # => SELECT * from articles LIMIT 10 + # end + # end + # end + # end + # + # *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+. + def with_scope(scope = {}, action = :merge, &block) + # If another Active Record class has been passed in, get its current scope + scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope) + + previous_scope = self.current_scope + + if scope.is_a?(Hash) + # Dup first and second level of hash (method and params). + scope = scope.dup + scope.each do |method, params| + scope[method] = params.dup unless params == true + end + + scope.assert_valid_keys([ :find, :create ]) + relation = construct_finder_arel(scope[:find] || {}) + relation.default_scoped = true unless action == :overwrite + + if previous_scope && previous_scope.create_with_value && scope[:create] + scope_for_create = if action == :merge + previous_scope.create_with_value.merge(scope[:create]) + else + scope[:create] + end + + relation = relation.create_with(scope_for_create) + else + scope_for_create = scope[:create] + scope_for_create ||= previous_scope.create_with_value if previous_scope + relation = relation.create_with(scope_for_create) if scope_for_create + end + + scope = relation + end + + scope = previous_scope.merge(scope) if previous_scope && action == :merge + + self.current_scope = scope + begin + yield + ensure + self.current_scope = previous_scope + end + end + + protected + + # Works like with_scope, but discards any nested properties. + def with_exclusive_scope(method_scoping = {}, &block) + if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } + raise ArgumentError, <<-MSG + New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: + + User.unscoped.where(:active => true) + + Or call unscoped with a block: + + User.unscoped do + User.where(:active => true).all + end + + MSG + end + with_scope(method_scoping, :overwrite, &block) + end + + def current_scope #:nodoc: + Thread.current["#{self}_current_scope"] + end + + def current_scope=(scope) #:nodoc: + Thread.current["#{self}_current_scope"] = scope + end + + private + + def construct_finder_arel(options = {}, scope = nil) + relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options + relation = scope.merge(relation) if scope + relation + end + + end + + def populate_with_current_scope_attributes + return unless self.class.scope_attributes? + + self.class.scope_attributes.each do |att,value| + send("#{att}=", value) if respond_to?("#{att}=") + end + end + + end +end diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb new file mode 100644 index 0000000000..5f05d146f2 --- /dev/null +++ b/activerecord/lib/active_record/scoping/default.rb @@ -0,0 +1,142 @@ +require 'active_support/concern' + +module ActiveRecord + module Scoping + module Default + extend ActiveSupport::Concern + + included do + # Stores the default scope for the class + config_attribute :default_scopes + self.default_scopes = [] + end + + module ClassMethods + # Returns a scope for the model without the default_scope. + # + # class Post < ActiveRecord::Base + # def self.default_scope + # where :published => true + # end + # end + # + # Post.all # Fires "SELECT * FROM posts WHERE published = true" + # Post.unscoped.all # Fires "SELECT * FROM posts" + # + # This method also accepts a block. All queries inside the block will + # not use the default_scope: + # + # Post.unscoped { + # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10" + # } + # + # It is recommended to use the block form of unscoped because chaining + # unscoped with <tt>scope</tt> does not work. Assuming that + # <tt>published</tt> is a <tt>scope</tt>, the following two statements + # are equal: the default_scope is applied on both. + # + # Post.unscoped.published + # Post.published + def unscoped #:nodoc: + block_given? ? relation.scoping { yield } : relation + end + + def before_remove_const #:nodoc: + self.current_scope = nil + end + + protected + + # Use this macro in your model to set a default scope for all operations on + # the model. + # + # class Article < ActiveRecord::Base + # default_scope where(:published => true) + # end + # + # Article.all # => SELECT * FROM articles WHERE published = true + # + # The <tt>default_scope</tt> is also applied while creating/building a record. It is not + # applied while updating a record. + # + # Article.new.published # => true + # Article.create.published # => true + # + # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated: + # + # class Article < ActiveRecord::Base + # default_scope { where(:published_at => Time.now - 1.week) } + # end + # + # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt> + # macro, and it will be called when building the default scope.) + # + # If you use multiple <tt>default_scope</tt> declarations in your model then they will + # be merged together: + # + # class Article < ActiveRecord::Base + # default_scope where(:published => true) + # default_scope where(:rating => 'G') + # end + # + # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G' + # + # This is also the case with inheritance and module includes where the parent or module + # defines a <tt>default_scope</tt> and the child or including class defines a second one. + # + # If you need to do more complex things with a default scope, you can alternatively + # define it as a class method: + # + # class Article < ActiveRecord::Base + # def self.default_scope + # # Should return a scope, you can call 'super' here etc. + # end + # end + def default_scope(scope = {}) + scope = Proc.new if block_given? + self.default_scopes = default_scopes + [scope] + end + + def build_default_scope #:nodoc: + if method(:default_scope).owner != ActiveRecord::Scoping::Default::ClassMethods + evaluate_default_scope { default_scope } + elsif default_scopes.any? + evaluate_default_scope do + default_scopes.inject(relation) do |default_scope, scope| + if scope.is_a?(Hash) + default_scope.apply_finder_options(scope) + elsif !scope.is_a?(Relation) && scope.respond_to?(:call) + default_scope.merge(scope.call) + else + default_scope.merge(scope) + end + end + end + end + end + + def ignore_default_scope? #:nodoc: + Thread.current["#{self}_ignore_default_scope"] + end + + def ignore_default_scope=(ignore) #:nodoc: + Thread.current["#{self}_ignore_default_scope"] = ignore + end + + # The ignore_default_scope flag is used to prevent an infinite recursion situation where + # a default scope references a scope which has a default scope which references a scope... + def evaluate_default_scope + return if ignore_default_scope? + + begin + self.ignore_default_scope = true + yield + ensure + self.ignore_default_scope = false + end + end + + end + end + end +end diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb new file mode 100644 index 0000000000..0edc3f1dcc --- /dev/null +++ b/activerecord/lib/active_record/scoping/named.rb @@ -0,0 +1,202 @@ +require 'active_support/core_ext/array' +require 'active_support/core_ext/hash/except' +require 'active_support/core_ext/kernel/singleton_class' +require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/class/attribute' + +module ActiveRecord + # = Active Record Named \Scopes + module Scoping + module Named + extend ActiveSupport::Concern + + module ClassMethods + # Returns an anonymous \scope. + # + # posts = Post.scoped + # posts.size # Fires "select count(*) from posts" and returns the count + # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects + # + # fruits = Fruit.scoped + # fruits = fruits.where(:color => 'red') if options[:red_only] + # fruits = fruits.limit(10) if limited? + # + # Anonymous \scopes tend to be useful when procedurally generating complex + # queries, where passing intermediate values (\scopes) around as first-class + # objects is convenient. + # + # You can define a \scope that applies to all finders using + # ActiveRecord::Base.default_scope. + def scoped(options = nil) + if options + scoped.apply_finder_options(options) + else + if current_scope + current_scope.clone + else + scope = relation.clone + scope.default_scoped = true + scope + end + end + end + + ## + # Collects attributes from scopes that should be applied when creating + # an AR instance for the particular class this is called on. + def scope_attributes # :nodoc: + if current_scope + current_scope.scope_for_create + else + scope = relation.clone + scope.default_scoped = true + scope.scope_for_create + end + end + + ## + # Are there default attributes associated with this scope? + def scope_attributes? # :nodoc: + current_scope || default_scopes.any? + end + + # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query, + # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>. + # + # class Shirt < ActiveRecord::Base + # scope :red, where(:color => 'red') + # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) + # end + # + # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, + # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. + # + # Note that this is simply 'syntactic sugar' for defining an actual class method: + # + # class Shirt < ActiveRecord::Base + # def self.red + # where(:color => 'red') + # end + # end + # + # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it + # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance, + # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>. + # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable; + # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> + # all behave as if Shirt.red really was an Array. + # + # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce + # all shirts that are both red and dry clean only. + # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> + # returns the number of garments for which these criteria obtain. Similarly with + # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>. + # + # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which + # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If, + # + # class Person < ActiveRecord::Base + # has_many :shirts + # end + # + # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean + # only shirts. + # + # Named \scopes can also be procedural: + # + # class Shirt < ActiveRecord::Base + # scope :colored, lambda { |color| where(:color => color) } + # end + # + # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. + # + # On Ruby 1.9 you can use the 'stabby lambda' syntax: + # + # scope :colored, ->(color) { where(:color => color) } + # + # Note that scopes defined with \scope will be evaluated when they are defined, rather than + # when they are used. For example, the following would be incorrect: + # + # class Post < ActiveRecord::Base + # scope :recent, where('published_at >= ?', Time.current - 1.week) + # end + # + # The example above would be 'frozen' to the <tt>Time.current</tt> value when the <tt>Post</tt> + # class was defined, and so the resultant SQL query would always be the same. The correct + # way to do this would be via a lambda, which will re-evaluate the scope each time + # it is called: + # + # class Post < ActiveRecord::Base + # scope :recent, lambda { where('published_at >= ?', Time.current - 1.week) } + # end + # + # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: + # + # class Shirt < ActiveRecord::Base + # scope :red, where(:color => 'red') do + # def dom_id + # 'red_shirts' + # end + # end + # end + # + # Scopes can also be used while creating/building a record. + # + # class Article < ActiveRecord::Base + # scope :published, where(:published => true) + # end + # + # Article.published.new.published # => true + # Article.published.create.published # => true + # + # Class methods on your model are automatically available + # on scopes. Assuming the following setup: + # + # class Article < ActiveRecord::Base + # scope :published, where(:published => true) + # scope :featured, where(:featured => true) + # + # def self.latest_article + # order('published_at desc').first + # end + # + # def self.titles + # map(&:title) + # end + # + # end + # + # We are able to call the methods like this: + # + # Article.published.featured.latest_article + # Article.featured.titles + + def scope(name, scope_options = {}) + name = name.to_sym + valid_scope_name?(name) + extension = Module.new(&Proc.new) if block_given? + + scope_proc = lambda do |*args| + options = scope_options.respond_to?(:call) ? unscoped { scope_options.call(*args) } : scope_options + options = scoped.apply_finder_options(options) if options.is_a?(Hash) + + relation = scoped.merge(options) + + extension ? relation.extending(extension) : relation + end + + singleton_class.send(:redefine_method, name, &scope_proc) + end + + protected + + def valid_scope_name?(name) + if respond_to?(name, true) + logger.warn "Creating scope :#{name}. " \ + "Overwriting existing method #{self.name}.#{name}." + end + end + end + end + end +end diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb index 76c37cc367..e3bbd06f7e 100644 --- a/activerecord/lib/active_record/session_store.rb +++ b/activerecord/lib/active_record/session_store.rb @@ -59,12 +59,12 @@ module ActiveRecord end def drop_table! - connection_pool.clear_table_cache!(table_name) + connection.schema_cache.clear_table_cache!(table_name) connection.drop_table table_name end def create_table! - connection_pool.clear_table_cache!(table_name) + connection.schema_cache.clear_table_cache!(table_name) connection.create_table(table_name) do |t| t.string session_id_column, :limit => 255 t.text data_column_name diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb new file mode 100644 index 0000000000..8cc84f81d0 --- /dev/null +++ b/activerecord/lib/active_record/store.rb @@ -0,0 +1,50 @@ +module ActiveRecord + # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. + # It's like a simple key/value store backed into your record when you don't care about being able to + # query that store outside the context of a single record. + # + # You can then declare accessors to this store that are then accessible just like any other attribute + # of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's + # already built around just accessing attributes on the model. + # + # Make sure that you declare the database column used for the serialized store as a text, so there's + # plenty of room. + # + # Examples: + # + # class User < ActiveRecord::Base + # store :settings, accessors: [ :color, :homepage ] + # end + # + # u = User.new(color: 'black', homepage: '37signals.com') + # u.color # Accessor stored attribute + # u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor + # + # # Add additional accessors to an existing store through store_accessor + # class SuperUser < User + # store_accessor :settings, :privileges, :servants + # end + module Store + extend ActiveSupport::Concern + + module ClassMethods + def store(store_attribute, options = {}) + serialize store_attribute, Hash + store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors + end + + def store_accessor(store_attribute, *keys) + Array(keys).flatten.each do |key| + define_method("#{key}=") do |value| + send(store_attribute)[key] = value + send("#{store_attribute}_will_change!") + end + + define_method(key) do + send(store_attribute)[key] + end + end + end + end + end +end
\ No newline at end of file diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb index ffe9b08dce..5398a14fc6 100644 --- a/activerecord/lib/active_record/test_case.rb +++ b/activerecord/lib/active_record/test_case.rb @@ -13,13 +13,6 @@ module ActiveRecord ActiveRecord::IdentityMap.clear end - # Backport skip to Ruby 1.8. test/unit doesn't support it, so just - # make it a noop. - unless instance_methods.map(&:to_s).include?("skip") - def skip(message) - end - end - def assert_date_from_db(expected, actual, message = nil) # SybaseAdapter doesn't have a separate column type just for dates, # so the time is in the string and incorrectly formatted @@ -56,18 +49,5 @@ module ActiveRecord ensure ActiveRecord::SQLCounter.ignored_sql = prev_ignored_sql end - - def with_kcode(kcode) - if RUBY_VERSION < '1.9' - orig_kcode, $KCODE = $KCODE, kcode - begin - yield - ensure - $KCODE = orig_kcode - end - else - yield - end - end end end diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index 4d5e469a7f..c717fdea47 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -33,7 +33,7 @@ module ActiveRecord extend ActiveSupport::Concern included do - class_attribute :record_timestamps, :instance_writer => false + config_attribute :record_timestamps, :instance_writer => true self.record_timestamps = true end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index d4870dd3f2..2c70d31b94 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -301,9 +301,9 @@ module ActiveRecord protected # Save the new record state and id of a record so it can be restored later if a transaction fails. - def remember_transaction_record_state #:nodoc + def remember_transaction_record_state #:nodoc: @_start_transaction_state ||= {} - @_start_transaction_state[:id] = id if self.class.primary_key? + @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key) unless @_start_transaction_state.include?(:new_record) @_start_transaction_state[:new_record] = @new_record end @@ -314,7 +314,7 @@ module ActiveRecord end # Clear the new record state and id of a record. - def clear_transaction_record_state #:nodoc + def clear_transaction_record_state #:nodoc: if defined?(@_start_transaction_state) @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 remove_instance_variable(:@_start_transaction_state) if @_start_transaction_state[:level] < 1 @@ -322,7 +322,7 @@ module ActiveRecord end # Restore the new record state and id of a record that was previously saved by a call to save_record_state. - def restore_transaction_record_state(force = false) #:nodoc + def restore_transaction_record_state(force = false) #:nodoc: if defined?(@_start_transaction_state) @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 if @_start_transaction_state[:level] < 1 @@ -341,12 +341,12 @@ module ActiveRecord end # Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed. - def transaction_record_state(state) #:nodoc + def transaction_record_state(state) #:nodoc: @_start_transaction_state[state] if defined?(@_start_transaction_state) end # Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks. - def transaction_include_action?(action) #:nodoc + def transaction_include_action?(action) #:nodoc: case action when :create transaction_record_state(:new_record) diff --git a/activerecord/lib/active_record/translation.rb b/activerecord/lib/active_record/translation.rb new file mode 100644 index 0000000000..ddcb5f2a7a --- /dev/null +++ b/activerecord/lib/active_record/translation.rb @@ -0,0 +1,22 @@ +module ActiveRecord + module Translation + include ActiveModel::Translation + + # Set the lookup ancestors for ActiveModel. + def lookup_ancestors #:nodoc: + klass = self + classes = [klass] + return classes if klass == ActiveRecord::Base + + while klass != klass.base_class + classes << klass = klass.superclass + end + classes + end + + # Set the i18n scope to overwrite ActiveModel. + def i18n_scope #:nodoc: + :activerecord + end + end +end diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb index 7af0352a31..9f072c4c39 100644 --- a/activerecord/lib/active_record/validations/associated.rb +++ b/activerecord/lib/active_record/validations/associated.rb @@ -2,8 +2,9 @@ module ActiveRecord module Validations class AssociatedValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) - return if (value.is_a?(Array) ? value : [value]).collect{ |r| r.nil? || r.valid? }.all? - record.errors.add(attribute, :invalid, options.merge(:value => value)) + if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any? + record.errors.add(attribute, :invalid, options.merge(:value => value)) + end end end diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index 484b1d369b..2e2ea8c42b 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -57,8 +57,8 @@ module ActiveRecord value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if column.text? if !options[:case_sensitive] && value && column.text? - # will use SQL LOWER function before comparison - relation = table[attribute].lower.eq(table.lower(value)) + # will use SQL LOWER function before comparison, unless it detects a case insensitive collation + relation = klass.connection.case_insensitive_comparison(table, attribute, column, value) else value = klass.connection.case_sensitive_modifier(value) relation = table[attribute].eq(value) diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb index 838aa8fb1e..0c35adc11d 100644 --- a/activerecord/lib/active_record/version.rb +++ b/activerecord/lib/active_record/version.rb @@ -1,7 +1,7 @@ module ActiveRecord module VERSION #:nodoc: - MAJOR = 3 - MINOR = 2 + MAJOR = 4 + MINOR = 0 TINY = 0 PRE = "beta" diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb index f6159deeeb..1509e34473 100644 --- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -3,7 +3,7 @@ require 'rails/generators/active_record' module ActiveRecord module Generators class MigrationGenerator < Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" def create_migration_file set_local_assigns! diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb index ce8d7eed42..d084a00ed7 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb @@ -2,14 +2,20 @@ class <%= migration_class_name %> < ActiveRecord::Migration <%- if migration_action == 'add' -%> def change <% attributes.each do |attribute| -%> - add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %> + add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %> + <%- if attribute.has_index? -%> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> + <%- end %> <%- end -%> end <%- else -%> def up <% attributes.each do |attribute| -%> <%- if migration_action -%> - <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><% end %> + <%= migration_action %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'add' %>, :<%= attribute.type %><%= attribute.inject_options %><% end %> + <% if attribute.has_index? && migration_action == 'add' %> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> + <% end -%> <%- end -%> <%- end -%> end @@ -17,7 +23,7 @@ class <%= migration_class_name %> < ActiveRecord::Migration def down <% attributes.reverse.each do |attribute| -%> <%- if migration_action -%> - <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><% end %> + <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><%= attribute.inject_options %><% end %> <%- end -%> <%- end -%> end diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index f7caa43ac8..99a022461e 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -3,7 +3,7 @@ require 'rails/generators/active_record' module ActiveRecord module Generators class ModelGenerator < Base - argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" + argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" check_class_collision @@ -26,6 +26,10 @@ module ActiveRecord template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke end + def attributes_with_index + attributes.select { |a| a.has_index? || (a.reference? && options[:indexes]) } + end + hook_for :test_framework protected diff --git a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb index 851930344a..3a3cf86d73 100644 --- a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb @@ -2,16 +2,14 @@ class <%= migration_class_name %> < ActiveRecord::Migration def change create_table :<%= table_name %> do |t| <% attributes.each do |attribute| -%> - t.<%= attribute.type %> :<%= attribute.name %> + t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %> <% end -%> <% if options[:timestamps] %> t.timestamps <% end -%> end -<% if options[:indexes] -%> -<% attributes.select {|attr| attr.reference? }.each do |attribute| -%> - add_index :<%= table_name %>, :<%= attribute.name %>_id -<% end -%> +<% attributes_with_index.each do |attribute| -%> + add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> <% end -%> end end diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb index 1c2942170e..267ea8bb6b 100644 --- a/activerecord/test/active_record/connection_adapters/fake_adapter.rb +++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb @@ -9,11 +9,16 @@ module ActiveRecord class FakeAdapter < AbstractAdapter attr_accessor :tables, :primary_keys + @columns = Hash.new { |h,k| h[k] = [] } + class << self + attr_reader :columns + end + def initialize(connection, logger) super @tables = [] @primary_keys = {} - @columns = Hash.new { |h,k| h[k] = [] } + @columns = self.class.columns end def primary_key(table) diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 94497e37c7..852fc0e26e 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -1,170 +1,163 @@ require "cases/helper" -class AdapterTest < ActiveRecord::TestCase - def setup - @connection = ActiveRecord::Base.connection - end - - def test_tables - tables = @connection.tables - assert tables.include?("accounts") - assert tables.include?("authors") - assert tables.include?("tasks") - assert tables.include?("topics") - end +module ActiveRecord + class AdapterTest < ActiveRecord::TestCase + def setup + @connection = ActiveRecord::Base.connection + end - def test_table_exists? - assert @connection.table_exists?("accounts") - assert !@connection.table_exists?("nonexistingtable") - end + def test_tables + tables = @connection.tables + assert tables.include?("accounts") + assert tables.include?("authors") + assert tables.include?("tasks") + assert tables.include?("topics") + end - def test_indexes - idx_name = "accounts_idx" - - if @connection.respond_to?(:indexes) - indexes = @connection.indexes("accounts") - assert indexes.empty? - - @connection.add_index :accounts, :firm_id, :name => idx_name - indexes = @connection.indexes("accounts") - assert_equal "accounts", indexes.first.table - # OpenBase does not have the concept of a named index - # Indexes are merely properties of columns. - assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter) - assert !indexes.first.unique - assert_equal ["firm_id"], indexes.first.columns - else - warn "#{@connection.class} does not respond to #indexes" + def test_table_exists? + assert @connection.table_exists?("accounts") + assert !@connection.table_exists?("nonexistingtable") + assert !@connection.table_exists?(nil) end - ensure - @connection.remove_index(:accounts, :name => idx_name) rescue nil - end + def test_indexes + idx_name = "accounts_idx" + + if @connection.respond_to?(:indexes) + indexes = @connection.indexes("accounts") + assert indexes.empty? + + @connection.add_index :accounts, :firm_id, :name => idx_name + indexes = @connection.indexes("accounts") + assert_equal "accounts", indexes.first.table + # OpenBase does not have the concept of a named index + # Indexes are merely properties of columns. + assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter) + assert !indexes.first.unique + assert_equal ["firm_id"], indexes.first.columns + else + warn "#{@connection.class} does not respond to #indexes" + end - def test_current_database - if @connection.respond_to?(:current_database) - assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database + ensure + @connection.remove_index(:accounts, :name => idx_name) rescue nil end - end - if current_adapter?(:MysqlAdapter) - def test_charset - assert_not_nil @connection.charset - assert_not_equal 'character_set_database', @connection.charset - assert_equal @connection.show_variable('character_set_database'), @connection.charset + def test_current_database + if @connection.respond_to?(:current_database) + assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database + end end - def test_collation - assert_not_nil @connection.collation - assert_not_equal 'collation_database', @connection.collation - assert_equal @connection.show_variable('collation_database'), @connection.collation - end + if current_adapter?(:MysqlAdapter) + def test_charset + assert_not_nil @connection.charset + assert_not_equal 'character_set_database', @connection.charset + assert_equal @connection.show_variable('character_set_database'), @connection.charset + end - def test_show_nonexistent_variable_returns_nil - assert_nil @connection.show_variable('foo_bar_baz') - end + def test_collation + assert_not_nil @connection.collation + assert_not_equal 'collation_database', @connection.collation + assert_equal @connection.show_variable('collation_database'), @connection.collation + end - def test_not_specifying_database_name_for_cross_database_selects - begin - assert_nothing_raised do - ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) + def test_show_nonexistent_variable_returns_nil + assert_nil @connection.show_variable('foo_bar_baz') + end - config = ARTest.connection_config - ActiveRecord::Base.connection.execute( - "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ - "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" - ) + def test_not_specifying_database_name_for_cross_database_selects + begin + assert_nothing_raised do + ActiveRecord::Model.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database)) + + config = ARTest.connection_config + ActiveRecord::Model.connection.execute( + "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \ + "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses" + ) + end + ensure + ActiveRecord::Model.establish_connection 'arunit' end - ensure - ActiveRecord::Base.establish_connection 'arunit' end end - end - def test_table_alias - def @connection.test_table_alias_length() 10; end - class << @connection - alias_method :old_table_alias_length, :table_alias_length - alias_method :table_alias_length, :test_table_alias_length - end + def test_table_alias + def @connection.test_table_alias_length() 10; end + class << @connection + alias_method :old_table_alias_length, :table_alias_length + alias_method :table_alias_length, :test_table_alias_length + end - assert_equal 'posts', @connection.table_alias_for('posts') - assert_equal 'posts_comm', @connection.table_alias_for('posts_comments') - assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts') + assert_equal 'posts', @connection.table_alias_for('posts') + assert_equal 'posts_comm', @connection.table_alias_for('posts_comments') + assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts') - class << @connection - remove_method :table_alias_length - alias_method :table_alias_length, :old_table_alias_length + class << @connection + remove_method :table_alias_length + alias_method :table_alias_length, :old_table_alias_length + end end - end - # test resetting sequences in odd tables in postgreSQL - if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!) - require 'models/movie' - require 'models/subscriber' + # test resetting sequences in odd tables in postgreSQL + if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!) + require 'models/movie' + require 'models/subscriber' - def test_reset_empty_table_with_custom_pk - Movie.delete_all - Movie.connection.reset_pk_sequence! 'movies' - assert_equal 1, Movie.create(:name => 'fight club').id - end + def test_reset_empty_table_with_custom_pk + Movie.delete_all + Movie.connection.reset_pk_sequence! 'movies' + assert_equal 1, Movie.create(:name => 'fight club').id + end - if ActiveRecord::Base.connection.adapter_name != "FrontBase" - def test_reset_table_with_non_integer_pk - Subscriber.delete_all - Subscriber.connection.reset_pk_sequence! 'subscribers' - sub = Subscriber.new(:name => 'robert drake') - sub.id = 'bob drake' - assert_nothing_raised { sub.save! } + if ActiveRecord::Base.connection.adapter_name != "FrontBase" + def test_reset_table_with_non_integer_pk + Subscriber.delete_all + Subscriber.connection.reset_pk_sequence! 'subscribers' + sub = Subscriber.new(:name => 'robert drake') + sub.id = 'bob drake' + assert_nothing_raised { sub.save! } + end end end - end - def test_uniqueness_violations_are_translated_to_specific_exception - @connection.execute "INSERT INTO subscribers(nick) VALUES('me')" - assert_raises(ActiveRecord::RecordNotUnique) do + def test_uniqueness_violations_are_translated_to_specific_exception @connection.execute "INSERT INTO subscribers(nick) VALUES('me')" + assert_raises(ActiveRecord::RecordNotUnique) do + @connection.execute "INSERT INTO subscribers(nick) VALUES('me')" + end end - end - def test_foreign_key_violations_are_translated_to_specific_exception - unless @connection.adapter_name == 'SQLite' - assert_raises(ActiveRecord::InvalidForeignKey) do - # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method - if @connection.prefetch_primary_key? - id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) - @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" - else - @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + def test_foreign_key_violations_are_translated_to_specific_exception + unless @connection.adapter_name == 'SQLite' + assert_raises(ActiveRecord::InvalidForeignKey) do + # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method + if @connection.prefetch_primary_key? + id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) + @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" + else + @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + end end end end - end - def test_disable_referential_integrity - assert_nothing_raised do - @connection.disable_referential_integrity do - # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method - if @connection.prefetch_primary_key? - id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) - @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" - else - @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + def test_disable_referential_integrity + assert_nothing_raised do + @connection.disable_referential_integrity do + # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method + if @connection.prefetch_primary_key? + id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id")) + @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)" + else + @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)" + end + # should deleted created record as otherwise disable_referential_integrity will try to enable contraints after executed block + # and will fail (at least on Oracle) + @connection.execute "DELETE FROM fk_test_has_fk" end - # should deleted created record as otherwise disable_referential_integrity will try to enable contraints after executed block - # and will fail (at least on Oracle) - @connection.execute "DELETE FROM fk_test_has_fk" end end end - - def test_deprecated_visitor_for - visitor_klass = Class.new(Arel::Visitors::ToSql) - Arel::Visitors::VISITORS['fuuu'] = visitor_klass - pool = stub(:spec => stub(:config => { :adapter => 'fuuu' })) - visitor = assert_deprecated { - ActiveRecord::ConnectionAdapters::AbstractAdapter.visitor_for(pool) - } - assert visitor.is_a?(visitor_klass) - end end diff --git a/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb new file mode 100644 index 0000000000..97adb6b297 --- /dev/null +++ b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb @@ -0,0 +1,35 @@ +require "cases/helper" +require 'models/person' + +class MysqlCaseSensitivityTest < ActiveRecord::TestCase + class CollationTest < ActiveRecord::Base + validates_uniqueness_of :string_cs_column, :case_sensitive => false + validates_uniqueness_of :string_ci_column, :case_sensitive => false + end + + def test_columns_include_collation_different_from_table + assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation + assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation + end + + def test_case_sensitive + assert !CollationTest.columns_hash['string_ci_column'].case_sensitive? + assert CollationTest.columns_hash['string_cs_column'].case_sensitive? + end + + def test_case_insensitive_comparison_for_ci_column + CollationTest.create!(:string_ci_column => 'A') + invalid = CollationTest.new(:string_ci_column => 'a') + queries = assert_sql { invalid.save } + ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } + assert_no_match(/lower/i, ci_uniqueness_query) + end + + def test_case_insensitive_comparison_for_cs_column + CollationTest.create!(:string_cs_column => 'A') + invalid = CollationTest.new(:string_cs_column => 'a') + queries = assert_sql { invalid.save } + cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) } + assert_match(/lower/i, cs_uniqueness_query) + end +end diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 2a89430da9..fa2ba8d592 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -3,13 +3,13 @@ require "cases/helper" class MysqlConnectionTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Model.connection end def test_mysql_reconnect_attribute_after_connection_with_reconnect_true run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => true})) - assert ActiveRecord::Base.connection.raw_connection.reconnect + ActiveRecord::Model.establish_connection(orig_connection.merge({:reconnect => true})) + assert ActiveRecord::Model.connection.raw_connection.reconnect end end @@ -25,8 +25,8 @@ class MysqlConnectionTest < ActiveRecord::TestCase def test_mysql_reconnect_attribute_after_connection_with_reconnect_false run_without_connection do |orig_connection| - ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => false})) - assert !ActiveRecord::Base.connection.raw_connection.reconnect + ActiveRecord::Model.establish_connection(orig_connection.merge({:reconnect => false})) + assert !ActiveRecord::Model.connection.raw_connection.reconnect end end @@ -114,7 +114,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase # Test that MySQL allows multiple results for stored procedures if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) def test_multi_results - rows = ActiveRecord::Base.connection.select_rows('CALL ten();') + rows = ActiveRecord::Model.connection.select_rows('CALL ten();') assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" end @@ -123,11 +123,11 @@ class MysqlConnectionTest < ActiveRecord::TestCase private def run_without_connection - original_connection = ActiveRecord::Base.remove_connection + original_connection = ActiveRecord::Model.remove_connection begin yield original_connection ensure - ActiveRecord::Base.establish_connection(original_connection) + ActiveRecord::Model.establish_connection(original_connection) end end end diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb index 146b77a95c..7fe2c02c04 100644 --- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb @@ -17,11 +17,7 @@ module ActiveRecord end def test_client_encoding - if "<3".respond_to?(:encoding) - assert_equal Encoding::UTF_8, @conn.client_encoding - else - assert_equal 'utf8', @conn.client_encoding - end + assert_equal Encoding::UTF_8, @conn.client_encoding end def test_exec_insert_number @@ -41,13 +37,11 @@ module ActiveRecord value = result.rows.last.last - if "<3".respond_to?(:encoding) - # FIXME: this should probably be inside the mysql AR adapter? - value.force_encoding(@conn.client_encoding) + # FIXME: this should probably be inside the mysql AR adapter? + value.force_encoding(@conn.client_encoding) - # The strings in this file are utf-8, so transcode to utf-8 - value.encode!(Encoding::UTF_8) - end + # The strings in this file are utf-8, so transcode to utf-8 + value.encode!(Encoding::UTF_8) assert_equal str, value end diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb index a2155d1dd1..29f885c6e7 100644 --- a/activerecord/test/cases/adapters/mysql/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql/schema_test.rb @@ -13,8 +13,8 @@ module ActiveRecord table = Post.table_name @db_name = db - @omgpost = Class.new(Post) do - set_table_name "#{db}.#{table}" + @omgpost = Class.new(ActiveRecord::Base) do + self.table_name = "#{db}.#{table}" def self.name; 'Post'; end end end @@ -23,6 +23,10 @@ module ActiveRecord assert @omgpost.find(:first) end + def test_primary_key + assert_equal 'id', @omgpost.primary_key + end + def test_table_exists? name = @omgpost.table_name assert @connection.table_exists?(name), "#{name} table should exist" diff --git a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb new file mode 100644 index 0000000000..6bcc113482 --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb @@ -0,0 +1,35 @@ +require "cases/helper" +require 'models/person' + +class Mysql2CaseSensitivityTest < ActiveRecord::TestCase + class CollationTest < ActiveRecord::Base + validates_uniqueness_of :string_cs_column, :case_sensitive => false + validates_uniqueness_of :string_ci_column, :case_sensitive => false + end + + def test_columns_include_collation_different_from_table + assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation + assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation + end + + def test_case_sensitive + assert !CollationTest.columns_hash['string_ci_column'].case_sensitive? + assert CollationTest.columns_hash['string_cs_column'].case_sensitive? + end + + def test_case_insensitive_comparison_for_ci_column + CollationTest.create!(:string_ci_column => 'A') + invalid = CollationTest.new(:string_ci_column => 'a') + queries = assert_sql { invalid.save } + ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) } + assert_no_match(/lower/i, ci_uniqueness_query) + end + + def test_case_insensitive_comparison_for_cs_column + CollationTest.create!(:string_cs_column => 'A') + invalid = CollationTest.new(:string_cs_column => 'a') + queries = assert_sql { invalid.save } + cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)} + assert_match(/lower/i, cs_uniqueness_query) + end +end diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 26091c713b..8e2b9ca9a5 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -3,7 +3,7 @@ require "cases/helper" class MysqlConnectionTest < ActiveRecord::TestCase def setup super - @connection = ActiveRecord::Base.connection + @connection = ActiveRecord::Model.connection end def test_no_automatic_reconnection_after_timeout @@ -32,11 +32,11 @@ class MysqlConnectionTest < ActiveRecord::TestCase private def run_without_connection - original_connection = ActiveRecord::Base.remove_connection + original_connection = ActiveRecord::Model.remove_connection begin yield original_connection ensure - ActiveRecord::Base.establish_connection(original_connection) + ActiveRecord::Model.establish_connection(original_connection) end end end diff --git a/activerecord/test/cases/adapters/mysql2/explain_test.rb b/activerecord/test/cases/adapters/mysql2/explain_test.rb new file mode 100644 index 0000000000..68ed361aeb --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/explain_test.rb @@ -0,0 +1,26 @@ +require "cases/helper" +require 'models/developer' + +module ActiveRecord + module ConnectionAdapters + class Mysql2Adapter + class ExplainTest < ActiveRecord::TestCase + fixtures :developers + + def test_explain_for_one_query + explain = Developer.where(:id => 1).explain + assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain + assert_match %(developers | const), explain + end + + def test_explain_with_eager_loading + explain = Developer.where(:id => 1).includes(:audit_logs).explain + assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain + assert_match %(developers | const), explain + assert_match %(EXPLAIN for: SELECT `audit_logs`.* FROM `audit_logs` WHERE `audit_logs`.`developer_id` IN (1)), explain + assert_match %(audit_logs | ALL), explain + end + end + end + end +end diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb index 858d1da2dd..d5676bc522 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb @@ -13,8 +13,8 @@ module ActiveRecord table = Post.table_name @db_name = db - @omgpost = Class.new(Post) do - set_table_name "#{db}.#{table}" + @omgpost = Class.new(ActiveRecord::Base) do + self.table_name = "#{db}.#{table}" def self.name; 'Post'; end end end @@ -23,6 +23,10 @@ module ActiveRecord assert @omgpost.find(:first) end + def test_primary_key + assert_equal 'id', @omgpost.primary_key + end + def test_table_exists? name = @omgpost.table_name assert @connection.table_exists?(name), "#{name} table should exist" diff --git a/activerecord/test/cases/adapters/postgresql/explain_test.rb b/activerecord/test/cases/adapters/postgresql/explain_test.rb new file mode 100644 index 0000000000..0b61f61572 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/explain_test.rb @@ -0,0 +1,28 @@ +require "cases/helper" +require 'models/developer' + +module ActiveRecord + module ConnectionAdapters + class PostgreSQLAdapter + class ExplainTest < ActiveRecord::TestCase + fixtures :developers + + def test_explain_for_one_query + explain = Developer.where(:id => 1).explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match %(QUERY PLAN), explain + assert_match %(Index Scan using developers_pkey on developers), explain + end + + def test_explain_with_eager_loading + explain = Developer.where(:id => 1).includes(:audit_logs).explain + assert_match %(QUERY PLAN), explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match %(Index Scan using developers_pkey on developers), explain + assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" IN (1)), explain + assert_match %(Seq Scan on audit_logs), explain + end + end + end + end +end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb new file mode 100644 index 0000000000..33bf4478cc --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -0,0 +1,89 @@ +require "cases/helper" + +class PostgresqlHstoreTest < ActiveRecord::TestCase + class Hstore < ActiveRecord::Base + self.table_name = 'hstores' + end + + def setup + @connection = ActiveRecord::Base.connection + begin + @connection.transaction do + @connection.create_table('hstores') do |t| + t.hstore 'tags' + end + end + rescue ActiveRecord::StatementInvalid + return skip "do not test on PG without hstore" + end + end + + def teardown + @connection.execute 'drop table if exists hstores' + end + + def test_column + column = Hstore.columns.find { |c| c.name == 'tags' } + assert column + assert_equal :hstore, column.type + end + + def test_type_cast_hstore + column = Hstore.columns.find { |c| c.name == 'tags' } + assert column + + data = "\"1\"=>\"2\"" + hash = column.class.cast_hstore data + assert_equal({'1' => '2'}, hash) + assert_equal({'1' => '2'}, column.type_cast(data)) + end + + def test_select + @connection.execute "insert into hstores (tags) VALUES ('1=>2')" + x = Hstore.find :first + assert_equal({'1' => '2'}, x.tags) + end + + def test_select_multikey + @connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')" + x = Hstore.find :first + assert_equal({'1' => '2', '2' => '3'}, x.tags) + end + + def test_create + assert_cycle('a' => 'b', '1' => '2') + end + + def test_quotes + assert_cycle('a' => 'b"ar', '1"foo' => '2') + end + + def test_whitespace + assert_cycle('a b' => 'b ar', '1"foo' => '2') + end + + def test_backslash + assert_cycle('a\\b' => 'b\\ar', '1"foo' => '2') + end + + def test_comma + assert_cycle('a, b' => 'bar', '1"foo' => '2') + end + + def test_arrow + assert_cycle('a=>b' => 'bar', '1"foo' => '2') + end + + private + def assert_cycle hash + x = Hstore.create!(:tags => hash) + x.reload + assert_equal(hash, x.tags) + + # make sure updates work + x.tags = hash + x.save! + x.reload + assert_equal(hash, x.tags) + end +end diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 76c73e9dfa..18670b4177 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -10,32 +10,39 @@ class SchemaTest < ActiveRecord::TestCase INDEX_A_NAME = 'a_index_things_on_name' INDEX_B_NAME = 'b_index_things_on_different_columns_in_each_schema' INDEX_C_NAME = 'c_index_full_text_search' + INDEX_D_NAME = 'd_index_things_on_description_desc' INDEX_A_COLUMN = 'name' INDEX_B_COLUMN_S1 = 'email' INDEX_B_COLUMN_S2 = 'moment' INDEX_C_COLUMN = %q{(to_tsvector('english', coalesce(things.name, '')))} + INDEX_D_COLUMN = 'description' COLUMNS = [ 'id integer', 'name character varying(50)', 'email character varying(50)', + 'description character varying(100)', 'moment timestamp without time zone default now()' ] PK_TABLE_NAME = 'table_with_pk' class Thing1 < ActiveRecord::Base - set_table_name "test_schema.things" + self.table_name = "test_schema.things" end class Thing2 < ActiveRecord::Base - set_table_name "test_schema2.things" + self.table_name = "test_schema2.things" end class Thing3 < ActiveRecord::Base - set_table_name 'test_schema."things.table"' + self.table_name = 'test_schema."things.table"' end class Thing4 < ActiveRecord::Base - set_table_name 'test_schema."Things"' + self.table_name = 'test_schema."Things"' + end + + class Thing5 < ActiveRecord::Base + self.table_name = 'things' end def setup @@ -50,6 +57,8 @@ class SchemaTest < ActiveRecord::TestCase @connection.execute "CREATE INDEX #{INDEX_B_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_B_COLUMN_S2});" @connection.execute "CREATE INDEX #{INDEX_C_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING gin (#{INDEX_C_COLUMN});" @connection.execute "CREATE INDEX #{INDEX_C_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING gin (#{INDEX_C_COLUMN});" + @connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);" + @connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);" @connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{PK_TABLE_NAME} (id serial primary key)" end @@ -58,6 +67,18 @@ class SchemaTest < ActiveRecord::TestCase @connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE" end + def test_schema_change_with_prepared_stmt + altered = false + @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]] + @connection.exec_query "alter table developers add column zomg int", 'sql', [] + altered = true + @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]] + ensure + # We are not using DROP COLUMN IF EXISTS because that syntax is only + # supported by pg 9.X + @connection.exec_query("alter table developers drop column zomg", 'sql', []) if altered + end + def test_table_exists? [Thing1, Thing2, Thing3, Thing4].each do |klass| name = klass.table_name @@ -172,11 +193,15 @@ class SchemaTest < ActiveRecord::TestCase end def test_dump_indexes_for_schema_one - do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1) + do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN) end def test_dump_indexes_for_schema_two - do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2) + do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2, INDEX_D_COLUMN) + end + + def test_dump_indexes_for_schema_multiple_schemas_in_search_path + do_dump_index_tests_for_schema("public, #{SCHEMA_NAME}", INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN) end def test_with_uppercase_index_name @@ -236,6 +261,21 @@ class SchemaTest < ActiveRecord::TestCase end end + def test_prepared_statements_with_multiple_schemas + + @connection.schema_search_path = SCHEMA_NAME + Thing5.create(:id => 1, :name => "thing inside #{SCHEMA_NAME}", :email => "thing1@localhost", :moment => Time.now) + + @connection.schema_search_path = SCHEMA2_NAME + Thing5.create(:id => 1, :name => "thing inside #{SCHEMA2_NAME}", :email => "thing1@localhost", :moment => Time.now) + + @connection.schema_search_path = SCHEMA_NAME + assert_equal 1, Thing5.count + + @connection.schema_search_path = SCHEMA2_NAME + assert_equal 1, Thing5.count + end + def test_schema_exists? { 'public' => true, @@ -261,13 +301,16 @@ class SchemaTest < ActiveRecord::TestCase @connection.schema_search_path = "'$user', public" end - def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name) + def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name, third_index_column_name) with_schema_search_path(this_schema_name) do indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name} - assert_equal 2,indexes.size + assert_equal 3,indexes.size do_dump_index_assertions_for_one_index(indexes[0], INDEX_A_NAME, first_index_column_name) do_dump_index_assertions_for_one_index(indexes[1], INDEX_B_NAME, second_index_column_name) + do_dump_index_assertions_for_one_index(indexes[2], INDEX_D_NAME, third_index_column_name) + + assert_equal :desc, indexes.select{|i| i.name == INDEX_D_NAME}[0].orders[INDEX_D_COLUMN] end end diff --git a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb index a82c6f67d6..f1c4b85126 100644 --- a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb +++ b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb @@ -2,6 +2,16 @@ require 'cases/helper' module ActiveRecord::ConnectionAdapters class PostgreSQLAdapter < AbstractAdapter + class InactivePGconn + def query(*args) + raise PGError + end + + def status + PGconn::CONNECTION_BAD + end + end + class StatementPoolTest < ActiveRecord::TestCase def test_cache_is_per_pid return skip('must support fork') unless Process.respond_to?(:fork) @@ -18,6 +28,12 @@ module ActiveRecord::ConnectionAdapters Process.waitpid pid assert $?.success?, 'process should exit successfully' end + + def test_dealloc_does_not_raise_on_inactive_connection + cache = StatementPool.new InactivePGconn.new, 10 + cache['foo'] = 'bar' + assert_nothing_raised { cache.clear } + end end end end diff --git a/activerecord/test/cases/adapters/postgresql/utils_test.rb b/activerecord/test/cases/adapters/postgresql/utils_test.rb index 5f08f79171..9e7b08ef34 100644 --- a/activerecord/test/cases/adapters/postgresql/utils_test.rb +++ b/activerecord/test/cases/adapters/postgresql/utils_test.rb @@ -1,3 +1,5 @@ +require 'cases/helper' + class PostgreSQLUtilsTest < ActiveSupport::TestCase include ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils diff --git a/activerecord/test/cases/adapters/postgresql/view_test.rb b/activerecord/test/cases/adapters/postgresql/view_test.rb index 303ba9245a..66e07b71a0 100644 --- a/activerecord/test/cases/adapters/postgresql/view_test.rb +++ b/activerecord/test/cases/adapters/postgresql/view_test.rb @@ -14,7 +14,7 @@ class ViewTest < ActiveRecord::TestCase ] class ThingView < ActiveRecord::Base - set_table_name 'test_schema.view_things' + self.table_name = 'test_schema.view_things' end def setup diff --git a/activerecord/test/cases/adapters/sqlite3/explain_test.rb b/activerecord/test/cases/adapters/sqlite3/explain_test.rb new file mode 100644 index 0000000000..b227bce680 --- /dev/null +++ b/activerecord/test/cases/adapters/sqlite3/explain_test.rb @@ -0,0 +1,26 @@ +require "cases/helper" +require 'models/developer' + +module ActiveRecord + module ConnectionAdapters + class SQLite3Adapter + class ExplainTest < ActiveRecord::TestCase + fixtures :developers + + def test_explain_for_one_query + explain = Developer.where(:id => 1).explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain) + end + + def test_explain_with_eager_loading + explain = Developer.where(:id => 1).includes(:audit_logs).explain + assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain + assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain) + assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" IN (1)), explain + assert_match(/(SCAN )?TABLE audit_logs/, explain) + end + end + end + end +end diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 2b598220ee..17bde6cb62 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -5,6 +5,8 @@ require 'models/owner' module ActiveRecord module ConnectionAdapters class SQLite3AdapterTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + class DualEncoding < ActiveRecord::Base end @@ -21,8 +23,6 @@ module ActiveRecord end def test_column_types - return skip('only test encoding on 1.9') unless "<3".encoding_aware? - owner = Owner.create!(:name => "hello".encode('ascii-8bit')) owner.reload select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ', ' @@ -142,8 +142,6 @@ module ActiveRecord end def test_quote_binary_column_escapes_it - return unless "<3".respond_to?(:encode) - DualEncoding.connection.execute(<<-eosql) CREATE TABLE dual_encodings ( id integer PRIMARY KEY AUTOINCREMENT, @@ -155,6 +153,9 @@ module ActiveRecord binary = DualEncoding.new :name => 'いただきます!', :data => str binary.save! assert_equal str, binary.data + + ensure + DualEncoding.connection.drop_table('dual_encodings') end def test_execute diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb index ff376a68d8..90e5609782 100644 --- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb @@ -61,15 +61,31 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_cascaded_eager_association_loading_with_duplicated_includes - categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null") + categories = Category.includes(:categorizations).includes(:categorizations => :author) + assert_nothing_raised do + assert_equal Category.count, categories.count + assert_equal Category.count, categories.all.size + end + end + + def test_cascaded_eager_association_loading_with_twice_includes_edge_cases + categories = Category.includes(:categorizations => :author).includes(:categorizations => :post) + assert_nothing_raised do + assert_equal Category.count, categories.count + assert_equal Category.count, categories.all.size + end + end + + def test_cascaded_eager_association_loading_with_duplicated_eager_load + categories = Category.eager_load(:categorizations).eager_load(:categorizations => :author).where("categorizations.id is not null") assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.all.size end end - def test_cascaded_eager_association_loading_with_twice_includes_edge_cases - categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null") + def test_cascaded_eager_association_loading_with_twice_eager_load_edge_cases + categories = Category.eager_load(:categorizations => :author).eager_load(:categorizations => :post).where("posts.id is not null") assert_nothing_raised do assert_equal 3, categories.count assert_equal 3, categories.all.size @@ -127,7 +143,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase silly.parent_id = 1 assert silly.save - topics = Topic.find(:all, :include => :replies, :order => 'topics.id, replies_topics.id') + topics = Topic.eager_load(:replies).order('topics.id, replies_topics.id').to_a assert_no_queries do assert_equal 2, topics[0].replies.size assert_equal 0, topics[1].replies.size @@ -142,7 +158,9 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_eager_association_loading_with_multiple_stis_and_order - author = Author.find(:first, :include => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :conditions => 'posts.id = 4') + author = Author.eager_load(:posts => [ :special_comments , :very_special_comment ]). + order('authors.name', 'comments.body', 'very_special_comments_posts.body'). + where('posts.id = 4').first assert_equal authors(:david), author assert_no_queries do author.posts.first.special_comments @@ -151,7 +169,9 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase end def test_eager_association_loading_of_stis_with_multiple_references - authors = Author.find(:all, :include => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :conditions => 'posts.id = 4') + authors = Author.eager_load(:posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } }). + order('comments.body, very_special_comments_posts.body'). + where('posts.id = 4') assert_equal [authors(:david)], authors assert_no_queries do authors.first.posts.first.special_comments.first.post.special_comments diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index d75791cab9..7965bb404c 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -4,7 +4,7 @@ require 'models/tagging' module Namespaced class Post < ActiveRecord::Base - set_table_name 'posts' + self.table_name = 'posts' has_one :tagging, :as => :taggable, :class_name => 'Tagging' end end diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 2cf9f89c3c..0964124a81 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -6,7 +6,6 @@ require 'models/comment' require 'models/category' require 'models/categorization' require 'models/tagging' -require 'active_support/core_ext/array/random_access' module Remembered extend ActiveSupport::Concern @@ -124,7 +123,7 @@ class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase assert_nothing_raised do # @davey_mcdave doesn't have any author_favorites includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author } - Author.all :include => includes, :conditions => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name' + Author.all :eager_load => includes, :conditions => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name' end end end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index c6e451fc57..ac9e3f29f9 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -55,13 +55,13 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_loading_with_one_association_with_non_preload - posts = Post.find(:all, :include => :last_comment, :order => 'comments.id DESC') + posts = Post.find(:all, :eager_load => :last_comment, :order => 'comments.id DESC') post = posts.find { |p| p.id == 1 } assert_equal Post.find(1).last_comment, post.last_comment end def test_loading_conditions_with_or - posts = authors(:david).posts.find(:all, :include => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'") + posts = authors(:david).posts.find(:all, :eager_load => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'") assert_nil posts.detect { |p| p.author_id != authors(:david).id }, "expected to find only david's posts" end @@ -165,7 +165,7 @@ class EagerAssociationTest < ActiveRecord::TestCase comment = car_post.comments.create!(:body => "hmm") categories = Category.find(:all, :conditions => ["posts.id=?", car_post.id], - :include => {:posts => :comments}) + :eager_load => {:posts => :comments}) categories.each do |category| assert_equal [comment], category.posts[0].comments end @@ -252,6 +252,41 @@ class EagerAssociationTest < ActiveRecord::TestCase end end + def test_nested_loading_through_has_one_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}) + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_order + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :order => 'author_addresses.id') + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_order_on_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :order => 'authors.id') + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_order_on_nested_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :order => 'posts.id') + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_conditions + aa = AuthorAddress.find(author_addresses(:david_address).id, :include => {:author => :posts}, :conditions => "author_addresses.id > 0") + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_conditions_on_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :conditions => "authors.id > 0") + assert_equal aa.author.posts.count, aa.author.posts.length + end + + def test_nested_loading_through_has_one_association_with_conditions_on_nested_association + aa = AuthorAddress.find(author_addresses(:david_address).id, :eager_load => {:author => :posts}, :conditions => "posts.id > 0") + assert_equal aa.author.posts.count, aa.author.posts.length + end + def test_eager_association_loading_with_belongs_to_and_foreign_keys pets = Pet.find(:all, :include => :owner) assert_equal 3, pets.length @@ -297,14 +332,14 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name assert_nothing_raised do - Comment.find(:all, :include => :post, :conditions => ['posts.id = ?',4]) + Comment.eager_load(:post).where('posts.id = ?',4).to_a end end def test_eager_association_loading_with_belongs_to_and_conditions_hash comments = [] assert_nothing_raised do - comments = Comment.find(:all, :include => :post, :conditions => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id') + comments = Comment.eager_load(:post).where(:posts => {:id => 4}).limit(3).order('comments.id').to_a end assert_equal 3, comments.length assert_equal [5,6,7], comments.collect { |c| c.id } @@ -316,20 +351,20 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_conditions_string_with_quoted_table_name quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id') assert_nothing_raised do - Comment.find(:all, :include => :post, :conditions => ["#{quoted_posts_id} = ?",4]) + Comment.eager_load(:post).where("#{quoted_posts_id} = ?",4).to_a end end def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name assert_nothing_raised do - Comment.find(:all, :include => :post, :order => 'posts.id') + Comment.eager_load(:post).order('posts.id').to_a end end def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id') assert_nothing_raised do - Comment.find(:all, :include => :post, :order => quoted_posts_id) + Comment.eager_load(:post).order(quoted_posts_id).to_a end end @@ -493,21 +528,21 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers - posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) assert_equal 2, posts.size - count = Post.count(:include => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) + count = Post.count(:eager_load => [ :author, :comments ], :limit => 2, :conditions => [ "authors.name = ?", 'David' ]) assert_equal count, posts.size end def test_eager_with_has_many_and_limit_and_high_offset - posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ]) + posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ]) assert_equal 0, posts.size end def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions assert_queries(1) do - posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, + posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]) assert_equal 0, posts.size end @@ -515,14 +550,14 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions assert_queries(1) do - posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, + posts = Post.find(:all, :eager_load => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }) assert_equal 0, posts.size end end def test_count_eager_with_has_many_and_limit_and_high_offset - posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => [ "authors.name = ?", 'David' ]) + posts = Post.eager_load(:author, :comments).limit(2).offset(10).where("authors.name = ?", 'David').count assert_equal 0, posts end @@ -534,7 +569,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_count_performed_on_a_has_many_association_with_multi_table_conditional author = authors(:david) author_posts_without_comments = author.posts.select { |post| post.comments.blank? } - assert_equal author_posts_without_comments.size, author.posts.count(:all, :include => :comments, :conditions => 'comments.id is null') + assert_equal author_posts_without_comments.size, author.posts.eager_load(:comments).where('comments.id is null').count end def test_eager_count_performed_on_a_has_many_through_association_with_multi_table_conditional @@ -571,14 +606,14 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_conditions_on_the_eagers posts = authors(:david).posts.find(:all, - :include => :comments, + :eager_load => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", :limit => 2 ) assert_equal 2, posts.size count = Post.count( - :include => [ :comments, :author ], + :eager_load => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", :limit => 2 ) @@ -588,7 +623,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers posts = nil Post.send(:with_scope, :find => { - :include => :comments, + :eager_load => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'" }) do posts = authors(:david).posts.find(:all, :limit => 2) @@ -596,7 +631,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end Post.send(:with_scope, :find => { - :include => [ :comments, :author ], + :eager_load => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')" }) do count = Post.count(:limit => 2) @@ -607,14 +642,14 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_scoped_and_explicit_conditions_on_the_eagers Post.send(:with_scope, :find => { :conditions => "1=1" }) do posts = authors(:david).posts.find(:all, - :include => :comments, + :eager_load => :comments, :conditions => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'", :limit => 2 ) assert_equal 2, posts.size count = Post.count( - :include => [ :comments, :author ], + :eager_load => [ :comments, :author ], :conditions => "authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')", :limit => 2 ) @@ -623,9 +658,9 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_with_scoped_order_using_association_limiting_without_explicit_scope - posts_with_explicit_order = Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :order => 'posts.id DESC', :limit => 2) + posts_with_explicit_order = Post.find(:all, :conditions => 'comments.id is not null', :eager_load => :comments, :order => 'posts.id DESC', :limit => 2) posts_with_scoped_order = Post.send(:with_scope, :find => {:order => 'posts.id DESC'}) do - Post.find(:all, :conditions => 'comments.id is not null', :include => :comments, :limit => 2) + Post.find(:all, :conditions => 'comments.id is not null', :eager_load => :comments, :limit => 2) end assert_equal posts_with_explicit_order, posts_with_scoped_order end @@ -738,17 +773,17 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_limited_eager_with_order - assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title)', :limit => 2, :offset => 1) - assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1) + assert_equal posts(:thinking, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title)', :limit => 2, :offset => 1) + assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1) end def test_limited_eager_with_multiple_order_columns - assert_equal posts(:thinking, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1) - assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :include => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1) + assert_equal posts(:thinking, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1) + assert_equal posts(:sti_post_and_comments, :sti_comments), Post.find(:all, :eager_load => [:author, :comments], :conditions => "authors.name = 'David'", :order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1) end def test_limited_eager_with_numeric_in_association - assert_equal people(:david, :susan), Person.find(:all, :include => [:readers, :primary_contact, :number1_fan], :conditions => "number1_fans_people.first_name like 'M%'", :order => 'people.id', :limit => 2, :offset => 0) + assert_equal people(:david, :susan), Person.find(:all, :eager_load => [:readers, :primary_contact, :number1_fan], :conditions => "number1_fans_people.first_name like 'M%'", :order => 'people.id', :limit => 2, :offset => 0) end def test_preload_with_interpolation @@ -863,11 +898,11 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_count_with_include if current_adapter?(:SybaseAdapter) - assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15") + assert_equal 3, assert_deprecated { authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15") } elsif current_adapter?(:OpenBaseAdapter) - assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15") + assert_equal 3, assert_deprecated { authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15") } else - assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15") + assert_equal 3, assert_deprecated { authors(:david).posts_with_comments.count(:conditions => "length(comments.body) > 15") } end end @@ -878,11 +913,11 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_conditions_on_join_table_with_include_and_limit - assert_equal 3, Developer.find(:all, :include => 'projects', :conditions => 'developers_projects.access_level = 1', :limit => 5).size + assert_equal 3, assert_deprecated { Developer.find(:all, :include => 'projects', :conditions => 'developers_projects.access_level = 1', :limit => 5).size } end def test_order_on_join_table_with_include_and_limit - assert_equal 5, Developer.find(:all, :include => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).size + assert_equal 5, assert_deprecated { Developer.find(:all, :include => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).size } end def test_eager_loading_with_order_on_joined_table_preloads @@ -979,9 +1014,9 @@ class EagerAssociationTest < ActiveRecord::TestCase expected = Firm.find(1).clients_using_primary_key.sort_by(&:name) # Oracle adapter truncates alias to 30 characters if current_adapter?(:OracleAdapter) - firm = Firm.find 1, :include => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name' + firm = Firm.find 1, :eager_load => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name' else - firm = Firm.find 1, :include => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name' + firm = Firm.find 1, :eager_load => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name' end assert_no_queries do assert_equal expected, firm.clients_using_primary_key @@ -998,7 +1033,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_include_has_one_using_primary_key expected = accounts(:signals37) - firm = Firm.find(:all, :include => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1} + firm = Firm.find(:all, :eager_load => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1} assert_no_queries do assert_equal expected, firm.account_using_primary_key end @@ -1051,13 +1086,20 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_join_eager_with_empty_order_should_generate_valid_sql assert_nothing_raised(ActiveRecord::StatementInvalid) do - Post.includes(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first + Post.eager_load(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first end end def test_join_eager_with_nil_order_should_generate_valid_sql assert_nothing_raised(ActiveRecord::StatementInvalid) do - Post.includes(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first + Post.eager_load(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first end end + + def test_deep_including_through_habtm + posts = Post.find(:all, :include => {:categories => :categorizations}, :order => "posts.id") + assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length } + assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length } + assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length } + end end diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index 8dc1423375..d7c489c2b5 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -36,11 +36,6 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase end def test_marshalling_extensions - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - david = developers(:david) assert_equal projects(:action_controller), david.projects.find_most_recent @@ -51,11 +46,6 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase end def test_marshalling_named_extensions - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - david = developers(:david) assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent @@ -71,6 +61,12 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer) end + def test_proxy_association_after_scoped + post = posts(:welcome) + assert_equal post.association(:comments), post.comments.the_association + assert_equal post.association(:comments), post.comments.scoped.the_association + end + private def extension_name(model) 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 34d90cc395..b91d9b5659 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 @@ -23,7 +23,7 @@ require 'models/treaty' require 'active_support/core_ext/string/conversions' class ProjectWithAfterCreateHook < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' has_and_belongs_to_many :developers, :class_name => "DeveloperForProjectWithAfterCreateHook", :join_table => "developers_projects", @@ -39,7 +39,7 @@ class ProjectWithAfterCreateHook < ActiveRecord::Base end class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' has_and_belongs_to_many :projects, :class_name => "ProjectWithAfterCreateHook", :join_table => "developers_projects", @@ -48,7 +48,7 @@ class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base end class ProjectWithSymbolsForKeys < ActiveRecord::Base - set_table_name 'projects' + self.table_name = 'projects' has_and_belongs_to_many :developers, :class_name => "DeveloperWithSymbolsForKeys", :join_table => :developers_projects, @@ -57,7 +57,7 @@ class ProjectWithSymbolsForKeys < ActiveRecord::Base end class DeveloperWithSymbolsForKeys < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' has_and_belongs_to_many :projects, :class_name => "ProjectWithSymbolsForKeys", :join_table => :developers_projects, @@ -66,7 +66,7 @@ class DeveloperWithSymbolsForKeys < ActiveRecord::Base end class DeveloperWithCounterSQL < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' has_and_belongs_to_many :projects, :class_name => "DeveloperWithCounterSQL", :join_table => "developers_projects", @@ -77,7 +77,7 @@ end class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects, - :parrots, :pirates, :treasures, :price_estimates, :tags, :taggings + :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings def setup_data_for_habtm_case ActiveRecord::Base.connection.execute('delete from countries_treaties') @@ -445,6 +445,26 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert david.projects(true).empty? end + def test_destroy_associations_destroys_multiple_associations + george = parrots(:george) + assert !george.pirates.empty? + assert !george.treasures.empty? + + assert_no_difference "Pirate.count" do + assert_no_difference "Treasure.count" do + george.destroy_associations + end + end + + join_records = Parrot.connection.select_all("SELECT * FROM parrots_pirates WHERE parrot_id = #{george.id}") + assert join_records.empty? + assert george.pirates(true).empty? + + join_records = Parrot.connection.select_all("SELECT * FROM parrots_treasures WHERE parrot_id = #{george.id}") + assert join_records.empty? + assert george.treasures(true).empty? + end + def test_deprecated_push_with_attributes_was_removed jamis = developers(:jamis) assert_raise(NoMethodError) do @@ -659,7 +679,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase end def test_join_table_alias - assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size + assert_equal 3, Developer.find(:all, :eager_load => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size end def test_join_with_group @@ -669,7 +689,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase end Project.columns.each { |c| group << "projects.#{c.name}" } - assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', :group => group.join(",")).size + assert_equal 3, Developer.find(:all, :eager_load => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL', :group => group.join(",")).size end def test_find_grouped @@ -805,12 +825,11 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase # clear cache possibly created by other tests david.projects.reset_column_information - # One query for columns, one for primary key - assert_queries(2) { david.projects.columns; david.projects.columns } + assert_queries(1) { david.projects.columns; david.projects.columns } ## and again to verify that reset_column_information clears the cache correctly david.projects.reset_column_information - assert_queries(2) { david.projects.columns; david.projects.columns } + assert_queries(1) { david.projects.columns; david.projects.columns } end def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index cddd2a6f8c..f1a341437f 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -8,6 +8,7 @@ require 'models/reply' require 'models/category' require 'models/post' require 'models/author' +require 'models/essay' require 'models/comment' require 'models/person' require 'models/reader' @@ -41,12 +42,37 @@ class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase end end +class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase + class Invoice < ActiveRecord::Base + has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items" + end + + def test_should_count_distinct_results + invoice = Invoice.new + invoice.custom_line_items << LineItem.new(:amount => 0) + invoice.custom_line_items << LineItem.new(:amount => 0) + invoice.save! + + assert_equal 1, invoice.custom_line_items.count + end +end + +class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase + fixtures :authors, :posts, :comments + + def test_should_generate_valid_sql + author = authors(:david) + # this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression + # if the reorder clauses are not correctly handled + assert author.posts_with_comments_sorted_by_comment_id.where('comments.id > 0').reorder('posts.comments_count DESC', 'posts.taggings_count DESC').last + end +end class HasManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :categories, :companies, :developers, :projects, :developers_projects, :topics, :authors, :comments, - :people, :posts, :readers, :taggings, :cars + :people, :posts, :readers, :taggings, :cars, :essays def setup Client.destroyed_client_ids.clear @@ -1375,6 +1401,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase firm.clients.last end end + + def test_custom_primary_key_on_new_record_should_fetch_with_query + author = Author.new(:name => "David") + assert !author.essays.loaded? + + assert_queries 1 do + assert_equal 1, author.essays.size + end + + assert_equal author.essays, Essay.find_all_by_writer_id("David") + + end + + def test_has_many_custom_primary_key + david = authors(:david) + assert_equal david.essays, Essay.find_all_by_writer_id("David") + end + + def test_blank_custom_primary_key_on_new_record_should_not_run_queries + author = Author.new + assert !author.essays.loaded? + + assert_queries 0 do + assert_equal 0, author.essays.size + end + end def test_calling_first_or_last_with_find_options_on_loaded_association_should_fetch_with_query firm = companies(:first_firm) diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index b703c96ec1..efe92c54c6 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -67,6 +67,31 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end end + def test_associate_existing_record_twice_should_add_records_twice + post = posts(:thinking) + person = people(:david) + + assert_difference 'post.people.count', 2 do + post.people << person + post.people << person + end + end + + def test_add_two_instance_and_then_deleting + post = posts(:thinking) + person = people(:david) + + post.people << person + post.people << person + + counts = ['post.people.count', 'post.people.to_a.count', 'post.readers.count', 'post.readers.to_a.count'] + assert_difference counts, -2 do + post.people.delete(person) + end + + assert !post.people.reload.include?(person) + end + def test_associating_new assert_queries(1) { posts(:thinking) } new_person = nil # so block binding catches it @@ -503,6 +528,12 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort end + def test_get_ids_for_has_many_through_with_conditions_should_not_preload + Tagging.create!(:taggable_type => 'Post', :taggable_id => posts(:welcome).id, :tag => tags(:misc)) + ActiveRecord::Associations::Preloader.expects(:new).never + posts(:welcome).misc_tag_ids + end + def test_get_ids_for_loaded_associations person = people(:michael) person.posts(true) @@ -816,7 +847,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_preloading_empty_through_association_via_joins person = Person.create!(:first_name => "Gaga") - person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').includes(:posts).to_a.first + person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').eager_load(:posts).to_a.first assert person.posts.loaded?, 'person.posts should be loaded' assert_equal [], person.posts @@ -825,4 +856,9 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_explicitly_joining_join_table assert_equal owners(:blackbeard).toys, owners(:blackbeard).toys.with_pet end + + def test_has_many_through_with_polymorphic_source + post = tags(:general).tagged_posts.create! :title => "foo", :body => "bar" + assert_equal [tags(:general)], post.reload.tags + end end diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 2503349c08..b04c5c7b54 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -111,7 +111,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_has_one_through_nonpreload_eagerloading members = assert_queries(1) do - Member.find(:all, :include => :club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback + Member.find(:all, :eager_load => :club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].club} @@ -119,7 +119,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_has_one_through_nonpreload_eager_loading_through_polymorphic members = assert_queries(1) do - Member.find(:all, :include => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback + Member.find(:all, :eager_load => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name') #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries {members[0].sponsor_club} @@ -128,7 +128,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save! members = assert_queries(1) do - Member.find(:all, :include => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC') #force fallback + Member.find(:all, :eager_load => :sponsor_club, :conditions => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC') #force fallback end assert_equal 1, members.size assert_not_nil assert_no_queries { members[0].sponsor_club } diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index e5e9ca6131..cb777b9f78 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -42,7 +42,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase end def test_join_conditions_allow_nil_associations - authors = Author.includes(:essays).where(:essays => {:id => nil}) + authors = Author.eager_load(:essays).where(:essays => {:id => nil}) assert_equal 2, authors.count end diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 76282213d8..61b341eaa4 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -104,7 +104,7 @@ class InverseHasOneTests < ActiveRecord::TestCase f.man.name = 'Mungo' assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance" - m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :face, :order => 'faces.id') + m = Man.find(:first, :conditions => {:name => 'Gordon'}, :eager_load => :face, :order => 'faces.id') f = m.face assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' @@ -189,7 +189,7 @@ class InverseHasManyTests < ActiveRecord::TestCase assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance" end - m = Man.find(:first, :conditions => {:name => 'Gordon'}, :include => :interests, :order => 'interests.id') + m = Man.find(:first, :conditions => {:name => 'Gordon'}, :eager_load => :interests, :order => 'interests.id') is = m.interests is.each do |i| assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" @@ -286,7 +286,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase m.face.description = 'pleasing' assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance" - f = Face.find(:first, :include => :man, :order => 'men.id', :conditions => {:description => 'trusting'}) + f = Face.find(:first, :eager_load => :man, :order => 'men.id', :conditions => {:description => 'trusting'}) m = f.man assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" f.description = 'gormless' @@ -369,7 +369,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase m.polymorphic_face.description = 'pleasing' assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance" - f = Face.find(:first, :conditions => {:description => 'confused'}, :include => :man, :order => 'men.id') + f = Face.find(:first, :conditions => {:description => 'confused'}, :eager_load => :man, :order => 'men.id') m = f.polymorphic_man assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance" f.description = 'gormless' diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 4ce8b85098..244d01da7d 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -362,7 +362,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end assert_raise ActiveRecord::EagerLoadPolymorphicError do - tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1') + tags(:general).taggings.eager_load(:taggable).where('bogus_table.column = 1').to_a end end @@ -419,7 +419,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end def test_eager_load_has_many_through_has_many - author = Author.find :first, :conditions => ['name = ?', 'David'], :include => :comments, :order => 'comments.id' + author = Author.where('name = ?', 'David').eager_load(:comments).order('comments.id').first SpecialComment.new; VerySpecialComment.new assert_no_queries do assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id) @@ -733,7 +733,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}" Post.find(post_id).update_column :type, class_name klass = Object.const_set(class_name, Class.new(ActiveRecord::Base)) - klass.set_table_name 'posts' + klass.table_name = 'posts' klass.send(association, association_name, :as => :taggable, :dependent => dependency) klass.find(post_id) end diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index 530f5212a2..b879ac9fb8 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -515,7 +515,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase end def test_nested_has_many_through_with_conditions_on_source_associations_preload - authors = assert_queries(4) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) } + authors = assert_queries(2) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) } blue = tags(:blue) assert_no_queries do @@ -545,13 +545,22 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase assert_equal [organizations(:nsa)], organizations end + def test_nested_has_many_through_should_not_be_autosaved + c = Categorization.new + c.author = authors(:david) + c.post_taggings.to_a + assert !c.post_taggings.empty? + c.save + assert !c.post_taggings.empty? + end + private def assert_includes_and_joins_equal(query, expected, association) actual = assert_queries(1) { query.joins(association).to_a.uniq } assert_equal expected, actual - actual = assert_queries(1) { query.includes(association).to_a.uniq } + actual = assert_queries(1) { query.eager_load(association).to_a.uniq } assert_equal expected, actual end end diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index ffe2993e0f..df657c1eb4 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require 'models/computer' require 'models/developer' require 'models/project' require 'models/company' @@ -28,7 +29,7 @@ class AssociationsTest < ActiveRecord::TestCase molecule.electrons.create(:name => 'electron_1') molecule.electrons.create(:name => 'electron_2') - liquids = Liquid.includes(:molecules => :electrons).where('molecules.id is not null') + liquids = Liquid.eager_load(:molecules => :electrons).where('molecules.id is not null') assert_equal 1, liquids[0].molecules.length end @@ -273,3 +274,18 @@ class OverridingAssociationsTest < ActiveRecord::TestCase ) end end + +class GeneratedMethodsTest < ActiveRecord::TestCase + fixtures :developers, :computers, :posts, :comments + def test_association_methods_override_attribute_methods_of_same_name + assert_equal(developers(:david), computers(:workstation).developer) + # this next line will fail if the attribute methods module is generated lazily + # after the association methods module is generated + assert_equal(developers(:david), computers(:workstation).developer) + assert_equal(developers(:david).id, computers(:workstation)[:developer]) + end + + def test_model_method_overrides_association_method + assert_equal(comments(:greetings).body, posts(:welcome).first_comment) + end +end diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index 814476ce73..0df9ffc0c5 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -14,8 +14,11 @@ module ActiveRecord def setup @klass = Class.new do + def self.superclass; Base; end + def self.active_record_super; Base; end + def self.base_class; self; end + include ActiveRecord::AttributeMethods - include ActiveRecord::AttributeMethods::Read def self.column_names %w{ one two three } @@ -24,10 +27,6 @@ module ActiveRecord def self.primary_key end - def self.primary_key? - false - end - def self.columns column_names.map { FakeColumn.new(name) } end @@ -37,9 +36,6 @@ module ActiveRecord [name, FakeColumn.new(name)] }] end - - def self.serialized_attributes; {}; end - def self.base_class; self; end end end diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index b1b41fed0d..b6cf26f978 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -35,6 +35,30 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert !t.attribute_present?("content") end + def test_attribute_present_with_booleans + b1 = Boolean.new + b1.value = false + assert b1.attribute_present?(:value) + + b2 = Boolean.new + b2.value = true + assert b2.attribute_present?(:value) + + b3 = Boolean.new + assert !b3.attribute_present?(:value) + + b4 = Boolean.new + b4.value = false + b4.save! + assert Boolean.find(b4.id).attribute_present?(:value) + end + + def test_caching_nil_primary_key + klass = Class.new(Minimalistic) + klass.expects(:reset_primary_key).returns(nil).once + 2.times { klass.primary_key } + end + def test_attribute_keys_on_new_instance t = Topic.new assert_equal nil, t.title, "The topics table has a title column, so it should be nil" @@ -78,7 +102,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_respond_to? topic = Topic.find(1) assert_respond_to topic, "title" - assert_respond_to topic, "_title" assert_respond_to topic, "title?" assert_respond_to topic, "title=" assert_respond_to topic, :title @@ -95,9 +118,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert_not_nil keyboard.key_number assert_equal keyboard.key_number, keyboard.id assert keyboard.respond_to?('key_number') - assert keyboard.respond_to?('_key_number') assert keyboard.respond_to?('id') - assert keyboard.respond_to?('_id') end # Syck calls respond_to? before actually calling initialize @@ -489,6 +510,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end + def test_write_time_to_date_attributes + in_time_zone "Pacific Time (US & Canada)" do + record = @target.new + record.last_read = Time.utc(2010, 1, 1, 10) + assert_equal Date.civil(2010, 1, 1), record.last_read + end + end + def test_time_attributes_are_retrieved_in_current_time_zone in_time_zone "Pacific Time (US & Canada)" do utc_time = Time.utc(2008, 1, 1) @@ -524,6 +553,17 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end + def test_setting_time_zone_aware_read_attribute + utc_time = Time.utc(2008, 1, 1) + cst_time = utc_time.in_time_zone("Central Time (US & Canada)") + in_time_zone "Pacific Time (US & Canada)" do + record = @target.create(:written_on => cst_time).reload + assert_equal utc_time, record[:written_on] + assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record[:written_on].time_zone + assert_equal Time.utc(2007, 12, 31, 16), record[:written_on].time + end + end + def test_setting_time_zone_aware_attribute_with_string utc_time = Time.utc(2008, 1, 1) (-11..13).each do |timezone_offset| @@ -543,6 +583,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase record = @target.new record.written_on = ' ' assert_nil record.written_on + assert_nil record[:written_on] end end @@ -657,7 +698,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase topic = Topic.new(:id => 5) topic.id = 5 - topic.method(:id).owner.send(:remove_method, :id) + topic.method(:id).owner.send(:undef_method, :id) assert_deprecated do assert_equal 5, topic.id @@ -666,19 +707,39 @@ class AttributeMethodsTest < ActiveRecord::TestCase Topic.undefine_attribute_methods end + def test_read_attribute_with_nil_should_not_asplode + assert_equal nil, Topic.new.read_attribute(nil) + end + + # If B < A, and A defines an accessor for 'foo', we don't want to override + # that by defining a 'foo' method in the generated methods module for B. + # (That module will be inserted between the two, e.g. [B, <GeneratedAttributes>, A].) + def test_inherited_custom_accessors + klass = Class.new(ActiveRecord::Base) do + self.table_name = "topics" + self.abstract_class = true + def title; "omg"; end + def title=(val); self.author_name = val; end + end + subklass = Class.new(klass) + [klass, subklass].each(&:define_attribute_methods) + + topic = subklass.find(1) + assert_equal "omg", topic.title + + topic.title = "lol" + assert_equal "lol", topic.author_name + end + private def cached_columns - @cached_columns ||= (time_related_columns_on_topic + serialized_columns_on_topic).map(&:name) + @cached_columns ||= time_related_columns_on_topic.map(&:name) end def time_related_columns_on_topic Topic.columns.select { |c| c.type.in?([:time, :date, :datetime, :timestamp]) } end - def serialized_columns_on_topic - Topic.columns.select { |c| Topic.serialized_attributes.include?(c.name) } - end - def in_time_zone(zone) old_zone = Time.zone old_tz = ActiveRecord::Base.time_zone_aware_attributes diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 4ad2cdfc7e..4c3f2bda57 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -347,6 +347,17 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test client.save! assert_no_queries { assert_equal apple, client.firm } end + + def test_validation_does_not_validate_stale_association_target + valid_developer = Developer.create!(:name => "Dude", :salary => 50_000) + invalid_developer = Developer.new() + + auditlog = AuditLog.new(:message => "foo") + auditlog.developer = invalid_developer + auditlog.developer_id = valid_developer.id + + assert auditlog.valid? + end end class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 77fd1d2fad..80a660717e 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -23,6 +23,7 @@ require 'models/edge' require 'models/joke' require 'models/bulb' require 'models/bird' +require 'models/teapot' require 'rexml/document' require 'active_support/core_ext/exception' require 'bcrypt' @@ -69,6 +70,16 @@ end class BasicsTest < ActiveRecord::TestCase fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts + def test_generated_methods_modules + modules = Computer.ancestors + assert modules.include?(Computer::GeneratedFeatureMethods) + assert_equal(Computer::GeneratedFeatureMethods, Computer.generated_feature_methods) + assert(modules.index(Computer.generated_attribute_methods) > modules.index(Computer.generated_feature_methods), + "generated_attribute_methods must be higher in inheritance hierarchy than generated_feature_methods") + assert_not_equal Computer.generated_feature_methods, Post.generated_feature_methods + assert(modules.index(Computer.generated_attribute_methods) < modules.index(ActiveRecord::Base.ancestors[1])) + end + def test_column_names_are_escaped conn = ActiveRecord::Base.connection classname = conn.class.name[/[^:]*$/] @@ -97,6 +108,10 @@ class BasicsTest < ActiveRecord::TestCase assert pk.primary, 'nick should be primary key' end + def test_primary_key_with_no_id + assert_nil Edge.primary_key + end + unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter) def test_limit_with_comma assert_nothing_raised do @@ -557,10 +572,12 @@ class BasicsTest < ActiveRecord::TestCase weird = Weird.create('a$b' => 'value') weird.reload assert_equal 'value', weird.send('a$b') + assert_equal 'value', weird.read_attribute('a$b') weird.update_column('a$b', 'value2') weird.reload assert_equal 'value2', weird.send('a$b') + assert_equal 'value2', weird.read_attribute('a$b') end def test_multiparameter_attributes_on_date @@ -1181,19 +1198,6 @@ class BasicsTest < ActiveRecord::TestCase assert(auto.id > 0) end - def quote_column_name(name) - "<#{name}>" - end - - def test_quote_keys - ar = AutoId.new - source = {"foo" => "bar", "baz" => "quux"} - actual = ar.send(:quote_columns, self, source) - inverted = actual.invert - assert_equal("<foo>", inverted["bar"]) - assert_equal("<baz>", inverted["quux"]) - end - def test_sql_injection_via_find assert_raise(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do Topic.find("123456 OR id > 0") @@ -1231,6 +1235,27 @@ class BasicsTest < ActiveRecord::TestCase assert_equal(myobj, topic.content) end + def test_serialized_attribute_in_base_class + Topic.serialize("content", Hash) + + hash = { 'content1' => 'value1', 'content2' => 'value2' } + important_topic = ImportantTopic.create("content" => hash) + assert_equal(hash, important_topic.content) + + important_topic.reload + assert_equal(hash, important_topic.content) + end + + def test_serialized_attribute_declared_in_subclass + hash = { 'important1' => 'value1', 'important2' => 'value2' } + important_topic = ImportantTopic.create("important" => hash) + assert_equal(hash, important_topic.important) + + important_topic.reload + assert_equal(hash, important_topic.important) + assert_equal(hash, important_topic.read_attribute(:important)) + end + def test_serialized_time_attribute myobj = Time.local(2008,1,1,1,0) topic = Topic.create("content" => myobj).reload @@ -1355,22 +1380,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal author_name, Topic.find(topic.id).author_name end - if RUBY_VERSION < '1.9' - def test_quote_chars - with_kcode('UTF8') do - str = 'The Narrator' - topic = Topic.create(:author_name => str) - assert_equal str, topic.author_name - - assert_kind_of ActiveSupport::Multibyte.proxy_class, str.mb_chars - topic = Topic.find_by_author_name(str.mb_chars) - - assert_kind_of Topic, topic - assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars" - end - end - end - def test_toggle_attribute assert !topics(:first).approved? topics(:first).toggle!(:approved) @@ -1397,37 +1406,12 @@ class BasicsTest < ActiveRecord::TestCase assert_equal dev, dev.reload end - def test_define_attr_method_with_value - k = Class.new( ActiveRecord::Base ) - k.send(:define_attr_method, :table_name, "foo") - assert_equal "foo", k.table_name - end - - def test_define_attr_method_with_block - k = Class.new( ActiveRecord::Base ) do - class << self - attr_accessor :foo_key - end - end - k.foo_key = "id" - k.send(:define_attr_method, :foo_key) { "sys_" + original_foo_key } - assert_equal "sys_id", k.foo_key - end - - def test_set_table_name_with_value - k = Class.new( ActiveRecord::Base ) - k.table_name = "foo" - assert_equal "foo", k.table_name - k.set_table_name "bar" - assert_equal "bar", k.table_name - end - def test_switching_between_table_name assert_difference("GoodJoke.count") do - Joke.set_table_name "cold_jokes" + Joke.table_name = "cold_jokes" Joke.create - Joke.set_table_name "funny_jokes" + Joke.table_name = "funny_jokes" Joke.create end end @@ -1435,48 +1419,30 @@ class BasicsTest < ActiveRecord::TestCase def test_quoted_table_name_after_set_table_name klass = Class.new(ActiveRecord::Base) - klass.set_table_name "foo" + klass.table_name = "foo" assert_equal "foo", klass.table_name assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name - klass.set_table_name "bar" + klass.table_name = "bar" assert_equal "bar", klass.table_name assert_equal klass.connection.quote_table_name("bar"), klass.quoted_table_name end - def test_set_table_name_with_block - k = Class.new( ActiveRecord::Base ) - k.set_table_name { "ks" } - assert_equal "ks", k.table_name - end - - def test_set_primary_key_with_value - k = Class.new( ActiveRecord::Base ) - k.primary_key = "foo" - assert_equal "foo", k.primary_key - k.set_primary_key "bar" - assert_equal "bar", k.primary_key - end - - def test_set_primary_key_with_block + def test_set_table_name_with_inheritance k = Class.new( ActiveRecord::Base ) - k.primary_key = 'id' - k.set_primary_key { "sys_" + original_primary_key } - assert_equal "sys_id", k.primary_key + def k.name; "Foo"; end + def k.table_name; super + "ks"; end + assert_equal "foosks", k.table_name end - def test_set_inheritance_column_with_value - k = Class.new( ActiveRecord::Base ) - k.inheritance_column = "foo" - assert_equal "foo", k.inheritance_column - k.set_inheritance_column "bar" - assert_equal "bar", k.inheritance_column - end - - def test_set_inheritance_column_with_block - k = Class.new( ActiveRecord::Base ) - k.set_inheritance_column { original_inheritance_column + "_id" } - assert_equal "type_id", k.inheritance_column + def test_sequence_name_with_abstract_class + ak = Class.new(ActiveRecord::Base) + ak.abstract_class = true + k = Class.new(ak) + k.table_name = "projects" + orig_name = k.sequence_name + return skip "sequences not supported by db" unless orig_name + assert_equal k.reset_sequence_name, orig_name end def test_count_with_join @@ -1669,10 +1635,7 @@ class BasicsTest < ActiveRecord::TestCase end def test_descends_from_active_record - # Tries to call Object.abstract_class? - assert_raise(NoMethodError) do - ActiveRecord::Base.descends_from_active_record? - end + assert !ActiveRecord::Base.descends_from_active_record? # Abstract subclass of AR::Base. assert LoosePerson.descends_from_active_record? @@ -1695,6 +1658,10 @@ class BasicsTest < ActiveRecord::TestCase # Concrete subclasses an abstract class which has a type column. assert !SubStiPost.descends_from_active_record? + + assert Teapot.descends_from_active_record? + assert !OtherTeapot.descends_from_active_record? + assert CoolTeapot.descends_from_active_record? end def test_find_on_abstract_base_class_doesnt_use_type_condition @@ -1728,7 +1695,7 @@ class BasicsTest < ActiveRecord::TestCase def test_inspect_instance topic = topics(:first) - assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), topic.inspect + assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", important: nil, approved: false, replies_count: 1, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), topic.inspect end def test_inspect_new_instance @@ -1757,10 +1724,18 @@ class BasicsTest < ActiveRecord::TestCase assert_equal "The First Topic", topics(:first).becomes(Reply).title end + def test_becomes_includes_errors + company = Company.new(:name => nil) + assert !company.valid? + original_errors = company.errors + client = company.becomes(Client) + assert_equal original_errors, client.errors + end + def test_silence_sets_log_level_to_error_in_block original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::DEBUG ActiveRecord::Base.silence do ActiveRecord::Base.logger.warn "warn" @@ -1774,7 +1749,7 @@ class BasicsTest < ActiveRecord::TestCase def test_silence_sets_log_level_back_to_level_before_yield original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::WARN ActiveRecord::Base.silence do end @@ -1786,7 +1761,7 @@ class BasicsTest < ActiveRecord::TestCase def test_benchmark_with_log_level original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.logger.level = Logger::WARN ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count } ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count } @@ -1801,10 +1776,8 @@ class BasicsTest < ActiveRecord::TestCase def test_benchmark_with_use_silence original_logger = ActiveRecord::Base.logger log = StringIO.new - ActiveRecord::Base.logger = Logger.new(log) - ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => true) { ActiveRecord::Base.logger.debug "Loud" } + ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" } - assert_no_match(/Loud/, log.string) assert_match(/Quiet/, log.string) ensure ActiveRecord::Base.logger = original_logger @@ -1836,9 +1809,9 @@ class BasicsTest < ActiveRecord::TestCase def test_clear_cache! # preheat cache - c1 = Post.columns + c1 = Post.connection.schema_cache.columns['posts'] ActiveRecord::Base.clear_cache! - c2 = Post.columns + c2 = Post.connection.schema_cache.columns['posts'] assert_not_equal c1, c2 end @@ -1855,11 +1828,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_marshal_round_trip - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - expected = posts(:welcome) marshalled = Marshal.dump(expected) actual = Marshal.load(marshalled) @@ -1868,11 +1836,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_marshal_new_record_round_trip - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - marshalled = Marshal.dump(Post.new) post = Marshal.load(marshalled) @@ -1880,11 +1843,6 @@ class BasicsTest < ActiveRecord::TestCase end def test_marshalling_with_associations - if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7" - return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \ - "to be a Ruby bug.") - end - post = Post.new post.comments.build @@ -1931,4 +1889,19 @@ class BasicsTest < ActiveRecord::TestCase dev.update_attribute(:updated_at, nil) assert_match(/\/#{dev.id}$/, dev.cache_key) end + + def test_uniq_delegates_to_scoped + scope = stub + Bird.stubs(:scoped).returns(mock(:uniq => scope)) + assert_equal scope, Bird.uniq + end + + def test_active_record_super + assert_equal ActiveRecord::Model, ActiveRecord::Base.active_record_super + assert_equal ActiveRecord::Base, Topic.active_record_super + assert_equal Topic, ImportantTopic.active_record_super + assert_equal ActiveRecord::Model, Teapot.active_record_super + assert_equal Teapot, OtherTeapot.active_record_super + assert_equal ActiveRecord::Model, CoolTeapot.active_record_super + end end diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb index 06c14cb108..f97aade311 100644 --- a/activerecord/test/cases/binary_test.rb +++ b/activerecord/test/cases/binary_test.rb @@ -12,7 +12,7 @@ unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter) def test_mixed_encoding str = "\x80" - str.force_encoding('ASCII-8BIT') if str.respond_to?(:force_encoding) + str.force_encoding('ASCII-8BIT') binary = Binary.new :name => 'いただきます!', :data => str binary.save! @@ -23,7 +23,7 @@ unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter) # Mysql adapter doesn't properly encode things, so we have to do it if current_adapter?(:MysqlAdapter) - name.force_encoding('UTF-8') if name.respond_to?(:force_encoding) + name.force_encoding('UTF-8') end assert_equal 'いただきます!', name end @@ -33,7 +33,7 @@ unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter) FIXTURES.each do |filename| data = File.read(ASSETS_ROOT + "/#{filename}") - data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding) + data.force_encoding('ASCII-8BIT') data.freeze bin = Binary.new(:data => data) diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index c38814713a..3f026e310f 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/company' +require "models/contract" require 'models/topic' require 'models/edge' require 'models/club' @@ -48,11 +49,11 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_get_maximum_of_field_with_include - assert_equal 55, Account.maximum(:credit_limit, :include => :firm, :conditions => "companies.name != 'Summit'") + assert_equal 55, Account.eager_load(:firm).where("companies.name != 'Summit'").maximum(:credit_limit) end def test_should_get_maximum_of_field_with_scoped_include - Account.send :with_scope, :find => { :include => :firm, :conditions => "companies.name != 'Summit'" } do + Account.eager_load(:firm).where("companies.name != 'Summit'").scoping do assert_equal 55, Account.maximum(:credit_limit) end end @@ -269,7 +270,7 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_not_modify_options_when_using_includes - options = {:conditions => 'companies.id > 1', :include => :firm} + options = {:include => :firm} options_copy = options.dup Account.count(:all, options) @@ -333,7 +334,9 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_perform_joined_include_when_referencing_included_tables - joined_count = Account.includes(:firm).where(:companies => {:name => '37signals'}).count + joined_count = assert_deprecated do + Account.includes(:firm).where(:companies => {:name => '37signals'}).count + end assert_equal 1, joined_count end @@ -446,4 +449,35 @@ class CalculationsTest < ActiveRecord::TestCase distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true] assert_equal distinct_authors_for_approved_count, 2 end + + def test_pluck + assert_equal [1,2,3,4], Topic.order(:id).pluck(:id) + end + + def test_pluck_type_cast + topic = topics(:first) + relation = Topic.where(:id => topic.id) + assert_equal [ topic.approved ], relation.pluck(:approved) + assert_equal [ topic.last_read ], relation.pluck(:last_read) + assert_equal [ topic.written_on ], relation.pluck(:written_on) + end + + def test_pluck_and_uniq + assert_equal [50, 53, 55, 60], Account.order(:credit_limit).uniq.pluck(:credit_limit) + end + + def test_pluck_in_relation + company = Company.first + contract = company.contracts.create! + assert_equal [contract.id], company.contracts.pluck(:id) + end + + def test_pluck_with_serialization + t = Topic.create!(:content => { :foo => :bar }) + assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content) + end + + def test_pluck_with_qualified_column_name + assert_equal [1,2,3,4], Topic.order(:id).pluck("topics.id") + end end diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 7f4d25790b..7690769226 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -1,7 +1,7 @@ require "cases/helper" class CallbackDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' class << self def callback_string(callback_method) @@ -48,7 +48,7 @@ class CallbackDeveloperWithFalseValidation < CallbackDeveloper end class ParentDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' attr_accessor :after_save_called before_validation {|record| record.after_save_called = true} end @@ -58,7 +58,7 @@ class ChildDeveloper < ParentDeveloper end class RecursiveCallbackDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' before_save :on_before_save after_save :on_after_save @@ -79,7 +79,7 @@ class RecursiveCallbackDeveloper < ActiveRecord::Base end class ImmutableDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' validates_inclusion_of :salary, :in => 50000..200000 @@ -98,7 +98,7 @@ class ImmutableDeveloper < ActiveRecord::Base end class ImmutableMethodDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' validates_inclusion_of :salary, :in => 50000..200000 @@ -118,7 +118,7 @@ class ImmutableMethodDeveloper < ActiveRecord::Base end class OnCallbacksDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' before_validation { history << :before_validation } before_validation(:on => :create){ history << :before_validation_on_create } @@ -138,7 +138,7 @@ class OnCallbacksDeveloper < ActiveRecord::Base end class CallbackCancellationDeveloper < ActiveRecord::Base - set_table_name 'developers' + self.table_name = 'developers' attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy diff --git a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb new file mode 100644 index 0000000000..7dc6e8afcb --- /dev/null +++ b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb @@ -0,0 +1,54 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class AbstractAdapterTest < ActiveRecord::TestCase + attr_reader :adapter + + def setup + @adapter = AbstractAdapter.new nil, nil + end + + def test_in_use? + # FIXME: change to refute in Rails 4.0 / mt + assert !adapter.in_use?, 'adapter is not in use' + assert adapter.lease, 'lease adapter' + assert adapter.in_use?, 'adapter is in use' + end + + def test_lease_twice + assert adapter.lease, 'should lease adapter' + assert !adapter.lease, 'should not lease adapter' + end + + def test_last_use + assert !adapter.last_use + adapter.lease + assert adapter.last_use + end + + def test_expire_mutates_in_use + assert adapter.lease, 'lease adapter' + assert adapter.in_use?, 'adapter is in use' + adapter.expire + assert !adapter.in_use?, 'adapter is in use' + end + + def test_close + pool = ConnectionPool.new(ConnectionSpecification.new({}, nil)) + pool.connections << adapter + adapter.pool = pool + + # Make sure the pool marks the connection in use + assert_equal adapter, pool.connection + assert adapter.in_use? + + # Close should put the adapter back in the pool + adapter.close + assert !adapter.in_use? + + assert_equal adapter, pool.connection + end + end + end +end diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index bd0d161838..dc99ac665c 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -8,6 +8,9 @@ module ActiveRecord @handler.establish_connection 'america', Base.connection_pool.spec @klass = Class.new do def self.name; 'america'; end + class << self + alias active_record_super superclass + end end @subklass = Class.new(@klass) do def self.name; 'north america'; end @@ -40,8 +43,6 @@ module ActiveRecord def test_retrieve_connection_pool_uses_superclass_pool_after_subclass_establish_and_remove @handler.establish_connection 'north america', Base.connection_pool.spec - assert_not_same @handler.retrieve_connection_pool(@klass), - @handler.retrieve_connection_pool(@subklass) @handler.remove_connection @subklass assert_same @handler.retrieve_connection_pool(@klass), diff --git a/activerecord/test/cases/connection_adapters/connection_specification_test.rb b/activerecord/test/cases/connection_adapters/connection_specification_test.rb new file mode 100644 index 0000000000..ea2196cda2 --- /dev/null +++ b/activerecord/test/cases/connection_adapters/connection_specification_test.rb @@ -0,0 +1,12 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ConnectionSpecificationTest < ActiveRecord::TestCase + def test_dup_deep_copy_config + spec = ConnectionSpecification.new({ :a => :b }, "bar") + assert_not_equal(spec.config.object_id, spec.dup.config.object_id) + end + end + end +end diff --git a/activerecord/test/cases/connection_adapters/schema_cache_test.rb b/activerecord/test/cases/connection_adapters/schema_cache_test.rb new file mode 100644 index 0000000000..42e39d534c --- /dev/null +++ b/activerecord/test/cases/connection_adapters/schema_cache_test.rb @@ -0,0 +1,44 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class SchemaCacheTest < ActiveRecord::TestCase + def setup + connection = ActiveRecord::Base.connection + @cache = SchemaCache.new connection + end + + def test_primary_key + assert_equal 'id', @cache.primary_keys['posts'] + end + + def test_primary_key_for_non_existent_table + assert_nil @cache.primary_keys['omgponies'] + end + + def test_caches_columns + 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'] + end + + def test_clearing + @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 + end + end + end +end diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb index f554ceef35..a1d1177289 100644 --- a/activerecord/test/cases/connection_management_test.rb +++ b/activerecord/test/cases/connection_management_test.rb @@ -25,40 +25,6 @@ module ActiveRecord assert ActiveRecord::Base.connection_handler.active_connections? end - class FakeBase < ActiveRecord::Base - def self.establish_connection spec - String === spec ? super : spec - end - end - - def test_url_host_no_db - spec = FakeBase.establish_connection 'postgres://foo?encoding=utf8' - assert_equal({ - :adapter => "postgresql", - :database => "", - :host => "foo", - :encoding => "utf8" }, spec) - end - - def test_url_host_db - spec = FakeBase.establish_connection 'postgres://foo/bar?encoding=utf8' - assert_equal({ - :adapter => "postgresql", - :database => "bar", - :host => "foo", - :encoding => "utf8" }, spec) - end - - def test_url_port - spec = FakeBase.establish_connection 'postgres://foo:123?encoding=utf8' - assert_equal({ - :adapter => "postgresql", - :database => "", - :port => 123, - :host => "foo", - :encoding => "utf8" }, spec) - end - def test_app_delegation manager = ConnectionManagement.new(@app) diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 8a0f453127..26842d3998 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -4,6 +4,8 @@ module ActiveRecord module ConnectionAdapters class ConnectionPoolTest < ActiveRecord::TestCase def setup + super + # Keep a duplicate pool so we do not bother others @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec @@ -18,73 +20,76 @@ module ActiveRecord end end - def test_active_connection? - assert !@pool.active_connection? - assert @pool.connection - assert @pool.active_connection? - @pool.release_connection - assert !@pool.active_connection? + def teardown + super + @pool.connections.each(&:close) end - def test_pool_caches_columns - columns = @pool.columns['posts'] - assert_equal columns, @pool.columns['posts'] + def test_full_pool_exception + assert_raises(PoolFullError) do + (@pool.size + 1).times do + @pool.checkout + end + end end - def test_pool_caches_columns_hash - columns_hash = @pool.columns_hash['posts'] - assert_equal columns_hash, @pool.columns_hash['posts'] - end + def test_reap_and_active + @pool.checkout + @pool.checkout + @pool.checkout + @pool.timeout = 0 - def test_clearing_column_cache - @pool.columns['posts'] - @pool.columns_hash['posts'] + connections = @pool.connections.dup - @pool.clear_cache! + @pool.reap - assert_equal 0, @pool.columns.size - assert_equal 0, @pool.columns_hash.size + assert_equal connections.length, @pool.connections.length end - def test_primary_key - assert_equal 'id', @pool.primary_keys['posts'] - end + def test_reap_inactive + @pool.checkout + @pool.checkout + @pool.checkout + @pool.timeout = 0 - def test_primary_key_for_non_existent_table - assert_equal 'id', @pool.primary_keys['omgponies'] - end + connections = @pool.connections.dup + connections.each do |conn| + conn.extend(Module.new { def active?; false; end; }) + end - def test_primary_key_is_set_on_columns - posts_columns = @pool.columns_hash['posts'] - assert posts_columns['id'].primary + @pool.reap - (posts_columns.keys - ['id']).each do |key| - assert !posts_columns[key].primary - end + assert_equal 0, @pool.connections.length + ensure + connections.each(&:close) end - def test_clear_stale_cached_connections! - pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec - - threads = [ - Thread.new { pool.connection }, - Thread.new { pool.connection }] + def test_remove_connection + conn = @pool.checkout + assert conn.in_use? - threads.map { |t| t.join } + length = @pool.connections.length + @pool.remove conn + assert conn.in_use? + assert_equal(length - 1, @pool.connections.length) + ensure + conn.close + end - pool.extend Module.new { - attr_accessor :checkins - def checkin conn - @checkins << conn - conn.object_id - end - } - pool.checkins = [] + def test_remove_connection_for_thread + conn = @pool.connection + @pool.remove conn + assert_not_equal(conn, @pool.connection) + ensure + conn.close + end - cleared_threads = pool.clear_stale_cached_connections! - assert((cleared_threads - threads.map { |x| x.object_id }).empty?, - "threads should have been removed") - assert_equal pool.checkins.length, threads.length + def test_active_connection? + assert !@pool.active_connection? + assert @pool.connection + assert @pool.active_connection? + @pool.release_connection + assert !@pool.active_connection? end def test_checkout_behaviour @@ -96,24 +101,16 @@ module ActiveRecord threads << Thread.new(i) do |pool_count| connection = pool.connection assert_not_nil connection + connection.close end end - threads.each {|t| t.join} + threads.each(&:join) Thread.new do - threads.each do |t| - thread_ids = pool.instance_variable_get(:@reserved_connections).keys - assert thread_ids.include?(t.object_id) - end - - pool.connection - threads.each do |t| - thread_ids = pool.instance_variable_get(:@reserved_connections).keys - assert !thread_ids.include?(t.object_id) - end - end.join() - + assert pool.connection + pool.connection.close + end.join end def test_automatic_reconnect= diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb new file mode 100644 index 0000000000..e6cb1b9521 --- /dev/null +++ b/activerecord/test/cases/connection_specification/resolver_test.rb @@ -0,0 +1,41 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ConnectionSpecification + class ResolverTest < ActiveRecord::TestCase + def resolve(spec) + Resolver.new(spec, {}).spec.config + end + + def test_url_host_no_db + spec = resolve 'mysql://foo?encoding=utf8' + assert_equal({ + :adapter => "mysql", + :database => "", + :host => "foo", + :encoding => "utf8" }, spec) + end + + def test_url_host_db + spec = resolve 'mysql://foo/bar?encoding=utf8' + assert_equal({ + :adapter => "mysql", + :database => "bar", + :host => "foo", + :encoding => "utf8" }, spec) + end + + def test_url_port + spec = resolve 'mysql://foo:123?encoding=utf8' + assert_equal({ + :adapter => "mysql", + :database => "", + :port => 123, + :host => "foo", + :encoding => "utf8" }, spec) + end + end + end + end +end diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb new file mode 100644 index 0000000000..6ae6f83446 --- /dev/null +++ b/activerecord/test/cases/explain_test.rb @@ -0,0 +1,101 @@ +require 'cases/helper' +require 'models/car' +require 'active_support/core_ext/string/strip' + +if ActiveRecord::Base.connection.supports_explain? + class ExplainTest < ActiveRecord::TestCase + fixtures :cars + + def base + ActiveRecord::Base + end + + def connection + base.connection + end + + def test_logging_query_plan + base.logger.expects(:warn).with do |message| + message.starts_with?('EXPLAIN for:') + end + + with_threshold(0) do + Car.where(:name => 'honda').all + end + end + + def test_collect_queries_for_explain + base.auto_explain_threshold_in_seconds = nil + queries = Thread.current[:available_queries_for_explain] = [] + + with_threshold(0) do + Car.where(:name => 'honda').all + end + + sql, binds = queries[0] + assert_match "SELECT", sql + assert_match "honda", sql + assert_equal [], binds + ensure + Thread.current[:available_queries_for_explain] = nil + end + + def test_collecting_queries_for_explain + result, queries = ActiveRecord::Base.collecting_queries_for_explain do + Car.where(:name => 'honda').all + end + + sql, binds = queries[0] + assert_match "SELECT", sql + assert_match "honda", sql + assert_equal [], binds + assert_equal [cars(:honda)], result + end + + def test_exec_explain_with_no_binds + sqls = %w(foo bar) + binds = [[], []] + queries = sqls.zip(binds) + + connection.stubs(:explain).returns('query plan foo', 'query plan bar') + expected = sqls.map {|sql| "EXPLAIN for: #{sql}\nquery plan #{sql}"}.join("\n") + assert_equal expected, base.exec_explain(queries) + end + + def test_exec_explain_with_binds + cols = [Object.new, Object.new] + cols[0].expects(:name).returns('wadus') + cols[1].expects(:name).returns('chaflan') + + sqls = %w(foo bar) + binds = [[[cols[0], 1]], [[cols[1], 2]]] + queries = sqls.zip(binds) + + connection.stubs(:explain).returns("query plan foo\n", "query plan bar\n") + expected = <<-SQL.strip_heredoc + EXPLAIN for: #{sqls[0]} [["wadus", 1]] + query plan foo + + EXPLAIN for: #{sqls[1]} [["chaflan", 2]] + query plan bar + SQL + assert_equal expected, base.exec_explain(queries) + end + + def test_silence_auto_explain + base.expects(:collecting_sqls_for_explain).never + base.logger.expects(:warn).never + base.silence_auto_explain do + with_threshold(0) { Car.all } + end + end + + def with_threshold(threshold) + current_threshold = base.auto_explain_threshold_in_seconds + base.auto_explain_threshold_in_seconds = threshold + yield + ensure + base.auto_explain_threshold_in_seconds = current_threshold + end + end +end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 3088ab012f..5b882f966b 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -57,6 +57,11 @@ class FinderTest < ActiveRecord::TestCase assert Topic.first.replies.exists? end + # ensures +exists?+ runs valid SQL by excluding order value + def test_exists_with_order + assert Topic.order(:id).uniq.exists? + end + def test_does_not_exist_with_empty_table_and_no_args_given Topic.delete_all assert !Topic.exists? @@ -369,6 +374,10 @@ class FinderTest < ActiveRecord::TestCase assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort end + def test_find_on_hash_conditions_with_array_of_integers_and_ranges + assert_equal [1,2,3,5,6,7,8,9], Comment.find(:all, :conditions => {:id => [1..2, 3, 5, 6..8, 9]}).map(&:id).sort + end + def test_find_on_multiple_hash_conditions assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }) assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) } @@ -1110,9 +1119,9 @@ class FinderTest < ActiveRecord::TestCase end def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct - assert_equal 2, Post.find(:all, :include => { :authors => :author_address }, :order => ' author_addresses.id DESC ', :limit => 2).size + assert_equal 2, Post.find(:all, :eager_load => { :authors => :author_address }, :order => ' author_addresses.id DESC ', :limit => 2).size - assert_equal 3, Post.find(:all, :include => { :author => :author_address, :authors => :author_address}, + assert_equal 3, Post.find(:all, :eager_load => { :author => :author_address, :authors => :author_address}, :order => ' author_addresses_authors.id DESC ', :limit => 3).size end @@ -1140,7 +1149,7 @@ class FinderTest < ActiveRecord::TestCase end def test_with_limiting_with_custom_select - posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id') + posts = Post.find(:all, :eager_load => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id') assert_equal 3, posts.size assert_equal [0, 1, 1], posts.map(&:author_id).sort end @@ -1154,7 +1163,7 @@ class FinderTest < ActiveRecord::TestCase end def test_find_one_message_with_custom_primary_key - Toy.set_primary_key :name + Toy.primary_key = :name begin Toy.find 'Hello World!' rescue ActiveRecord::RecordNotFound => e diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 866dcefbab..859bb7992b 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -1,31 +1,34 @@ -require "cases/helper" -require 'models/post' +require 'cases/helper' +require 'models/admin' +require 'models/admin/account' +require 'models/admin/randomly_named_c1' +require 'models/admin/user' require 'models/binary' -require 'models/topic' +require 'models/book' +require 'models/category' +require 'models/company' require 'models/computer' +require 'models/course' require 'models/developer' -require 'models/company' -require 'models/task' -require 'models/reply' require 'models/joke' -require 'models/course' -require 'models/category' +require 'models/matey' require 'models/parrot' require 'models/pirate' -require 'models/treasure' -require 'models/traffic_light' -require 'models/matey' +require 'models/post' +require 'models/randomly_named_c1' +require 'models/reply' require 'models/ship' -require 'models/book' -require 'models/admin' -require 'models/admin/account' -require 'models/admin/user' +require 'models/task' +require 'models/topic' +require 'models/traffic_light' +require 'models/treasure' require 'tempfile' class FixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_fixtures = false + # other_topics fixture should not be included here fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights FIXTURES = %w( accounts binaries companies customers @@ -48,11 +51,11 @@ class FixturesTest < ActiveRecord::TestCase def test_broken_yaml_exception badyaml = Tempfile.new ['foo', '.yml'] - badyaml.write 'a: !ruby.yaml.org,2002:str |\nfoo' + badyaml.write 'a: : ' badyaml.flush dir = File.dirname badyaml.path - name =File.basename badyaml.path, '.yml' + name = File.basename badyaml.path, '.yml' assert_raises(ActiveRecord::Fixture::FormatError) do ActiveRecord::Fixtures.create_fixtures(dir, name) end @@ -93,7 +96,7 @@ class FixturesTest < ActiveRecord::TestCase # Reset cache to make finds on the new table work ActiveRecord::Fixtures.reset_cache - ActiveRecord::Base.connection.create_table :prefix_topics_suffix do |t| + ActiveRecord::Base.connection.create_table :prefix_other_topics_suffix do |t| t.column :title, :string t.column :author_name, :string t.column :author_email_address, :string @@ -115,23 +118,36 @@ class FixturesTest < ActiveRecord::TestCase ActiveRecord::Base.table_name_prefix = 'prefix_' ActiveRecord::Base.table_name_suffix = '_suffix' - topics = create_fixtures("topics") - - first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'David'") - assert_equal("The First Topic", first_row["title"]) + other_topic_klass = Class.new(ActiveRecord::Base) do + def self.name + "OtherTopic" + end + end - second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_topics_suffix WHERE author_name = 'Mary'") - assert_nil(second_row["author_email_address"]) + topics = [create_fixtures("other_topics")].flatten.first # This checks for a caching problem which causes a bug in the fixtures # class-level configuration helper. assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create" + + first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'") + assert_not_nil first_row, "The prefix_other_topics_suffix table appears to be empty despite create_fixtures: the row with author_name = 'David' was not found" + assert_equal("The First Topic", first_row["title"]) + + second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'") + assert_nil(second_row["author_email_address"]) + + assert_equal :prefix_other_topics_suffix, topics.table_name.to_sym + # This assertion should preferably be the last in the list, because calling + # other_topic_klass.table_name sets a class-level instance variable + assert_equal :prefix_other_topics_suffix, other_topic_klass.table_name.to_sym + ensure # Restore prefix/suffix to its previous values ActiveRecord::Base.table_name_prefix = old_prefix ActiveRecord::Base.table_name_suffix = old_suffix - ActiveRecord::Base.connection.drop_table :prefix_topics_suffix rescue nil + ActiveRecord::Base.connection.drop_table :prefix_other_topics_suffix rescue nil end end @@ -179,7 +195,7 @@ class FixturesTest < ActiveRecord::TestCase #sanity check to make sure that this file never exists assert Dir[nonexistent_fixture_path+"*"].empty? - assert_raise(FixturesFileNotFound) do + assert_raise(Errno::ENOENT) do ActiveRecord::Fixtures.new( Account.connection, "companies", 'Company', nonexistent_fixture_path) end end @@ -213,7 +229,7 @@ class FixturesTest < ActiveRecord::TestCase def test_binary_in_fixtures data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read } - data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding) + data.force_encoding('ASCII-8BIT') data.freeze assert_equal data, @flowers.data end @@ -451,14 +467,36 @@ end class CustomConnectionFixturesTest < ActiveRecord::TestCase set_fixture_class :courses => Course fixtures :courses - # Set to false to blow away fixtures cache and ensure our fixtures are loaded - # and thus takes into account our set_fixture_class self.use_transactional_fixtures = false def test_connection assert_kind_of Course, courses(:ruby) assert_equal Course.connection, courses(:ruby).connection end + + def test_leaky_destroy + assert_nothing_raised { courses(:ruby) } + courses(:ruby).destroy + end + + def test_it_twice_in_whatever_order_to_check_for_fixture_leakage + test_leaky_destroy + end +end + +class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase + set_fixture_class :courses => Course + fixtures :courses + self.use_transactional_fixtures = true + + def test_leaky_destroy + assert_nothing_raised { courses(:ruby) } + courses(:ruby).destroy + end + + def test_it_twice_in_whatever_order_to_check_for_fixture_leakage + test_leaky_destroy + end end class InvalidTableNameFixturesTest < ActiveRecord::TestCase @@ -496,7 +534,9 @@ class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase end class FixturesBrokenRollbackTest < ActiveRecord::TestCase - def blank_setup; end + def blank_setup + @fixture_connections = [ActiveRecord::Base.connection] + end alias_method :ar_setup_fixtures, :setup_fixtures alias_method :setup_fixtures, :blank_setup alias_method :setup, :blank_setup @@ -707,3 +747,34 @@ class FixtureLoadingTest < ActiveRecord::TestCase ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine) end end + +class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase + ActiveRecord::Fixtures.reset_cache + + set_fixture_class :randomly_named_a9 => + ClassNameThatDoesNotFollowCONVENTIONS, + :'admin/randomly_named_a9' => + Admin::ClassNameThatDoesNotFollowCONVENTIONS, + 'admin/randomly_named_b0' => + Admin::ClassNameThatDoesNotFollowCONVENTIONS + + fixtures :randomly_named_a9, 'admin/randomly_named_a9', + :'admin/randomly_named_b0' + + def test_named_accessor_for_randomly_named_fixture_and_class + assert_kind_of ClassNameThatDoesNotFollowCONVENTIONS, + randomly_named_a9(:first_instance) + end + + def test_named_accessor_for_randomly_named_namespaced_fixture_and_class + assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS, + admin_randomly_named_a9(:first_instance) + assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS, + admin_randomly_named_b0(:second_instance) + end + + def test_table_name_is_defined_in_the_model + assert_equal :randomly_named_table, ActiveRecord::Fixtures::all_loaded_fixtures["admin/randomly_named_a9"].table_name + assert_equal :randomly_named_table, Admin::ClassNameThatDoesNotFollowCONVENTIONS.table_name + end +end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 6735bc521b..859c3d1947 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -8,6 +8,7 @@ require 'mocha' require 'active_record' require 'active_support/dependencies' +require 'active_support/logger' require 'support/config' require 'support/connection' @@ -68,14 +69,19 @@ module ActiveRecord cattr_accessor :log self.log = [] + attr_reader :ignore + + def initialize(ignore = self.class.ignored_sql) + @ignore = ignore + end + def call(name, start, finish, message_id, values) sql = values[:sql] # FIXME: this seems bad. we should probably have a better way to indicate # the query was cached - unless 'CACHE' == values[:name] - self.class.log << sql unless self.class.ignored_sql.any? { |r| sql =~ r } - end + return if 'CACHE' == values[:name] || ignore.any? { |x| x =~ sql } + self.class.log << sql end end @@ -85,7 +91,10 @@ end unless ENV['FIXTURE_DEBUG'] module ActiveRecord::TestFixtures::ClassMethods def try_to_load_dependency_with_silence(*args) - ActiveRecord::Base.logger.silence { try_to_load_dependency_without_silence(*args)} + old = ActiveRecord::Base.logger.level + ActiveRecord::Base.logger.level = ActiveSupport::Logger::ERROR + try_to_load_dependency_without_silence(*args) + ActiveRecord::Base.logger.level = old end alias_method_chain :try_to_load_dependency, :silence diff --git a/activerecord/test/cases/inclusion_test.rb b/activerecord/test/cases/inclusion_test.rb new file mode 100644 index 0000000000..8726ba5e51 --- /dev/null +++ b/activerecord/test/cases/inclusion_test.rb @@ -0,0 +1,113 @@ +require 'cases/helper' +require 'models/teapot' + +class BasicInclusionModelTest < ActiveRecord::TestCase + def test_basic_model + Teapot.create!(:name => "Ronnie Kemper") + assert_equal "Ronnie Kemper", Teapot.find(1).name + end + + def test_initialization + t = Teapot.new(:name => "Bob") + assert_equal "Bob", t.name + end + + def test_inherited_model + teapot = CoolTeapot.create!(:name => "Bob") + teapot.reload + + assert_equal "Bob", teapot.name + assert_equal "mmm", teapot.aaahhh + end + + def test_generated_feature_methods + assert Teapot < Teapot::GeneratedFeatureMethods + end + + def test_exists + t = Teapot.create!(:name => "Ronnie Kemper") + assert Teapot.exists?(t) + end + + def test_predicate_builder + t = Teapot.create!(:name => "Bob") + assert_equal "Bob", Teapot.where(:id => [t]).first.name + assert_equal "Bob", Teapot.where(:id => t).first.name + end + + def test_nested_model + assert_equal "ceiling_teapots", Ceiling::Teapot.table_name + end +end + +class InclusionUnitTest < ActiveRecord::TestCase + def setup + @klass = Class.new { include ActiveRecord::Model } + end + + def test_non_abstract_class + assert !@klass.abstract_class? + end + + def test_abstract_class + @klass.abstract_class = true + assert @klass.abstract_class? + end + + def test_establish_connection + assert @klass.respond_to?(:establish_connection) + assert ActiveRecord::Model.respond_to?(:establish_connection) + end + + def test_adapter_connection + name = "#{ActiveRecord::Base.connection_config[:adapter]}_connection" + assert @klass.respond_to?(name) + assert ActiveRecord::Model.respond_to?(name) + end + + def test_connection_handler + assert_equal ActiveRecord::Base.connection_handler, @klass.connection_handler + end + + def test_mirrored_configuration + ActiveRecord::Base.time_zone_aware_attributes = true + assert @klass.time_zone_aware_attributes + ActiveRecord::Base.time_zone_aware_attributes = false + assert !@klass.time_zone_aware_attributes + ensure + ActiveRecord::Base.time_zone_aware_attributes = false + end + + # Doesn't really test anything, but this is here to ensure warnings don't occur + def test_included_twice + @klass.send :include, ActiveRecord::Model + end + + def test_deprecation_proxy + assert_equal ActiveRecord::Model.name, ActiveRecord::Model::DeprecationProxy.name + assert_equal ActiveRecord::Base.superclass, assert_deprecated { ActiveRecord::Model::DeprecationProxy.superclass } + + sup, sup2 = nil, nil + ActiveSupport.on_load(:__test_active_record_model_deprecation) do + sup = superclass + sup2 = send(:superclass) + end + assert_deprecated do + ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, ActiveRecord::Model::DeprecationProxy) + end + assert_equal ActiveRecord::Base.superclass, sup + assert_equal ActiveRecord::Base.superclass, sup2 + end +end + +class InclusionFixturesTest < ActiveRecord::TestCase + fixtures :teapots + + def test_fixtured_record + assert_equal "Bob", teapots(:bob).name + end + + def test_timestamped_fixture + assert_not_nil teapots(:bob).created_at + end +end diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index b5d8314541..02df464469 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -65,7 +65,6 @@ class InheritanceTest < ActiveRecord::TestCase end def test_company_descends_from_active_record - assert_raise(NoMethodError) { ActiveRecord::Base.descends_from_active_record? } assert AbstractCompany.descends_from_active_record?, 'AbstractCompany should descend from ActiveRecord::Base' assert Company.descends_from_active_record?, 'Company should descend from ActiveRecord::Base' assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base' @@ -236,11 +235,11 @@ class InheritanceTest < ActiveRecord::TestCase c.save end [ Company, Firm, Client].each { |klass| klass.reset_column_information } - Company.set_inheritance_column('ruby_type') + Company.inheritance_column = 'ruby_type' end def switch_to_default_inheritance_column [ Company, Firm, Client].each { |klass| klass.reset_column_information } - Company.set_inheritance_column('type') + Company.inheritance_column = 'type' end end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index a809cd0aa7..65cd9f9755 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -13,8 +13,8 @@ require 'models/wheel' class LockWithoutDefault < ActiveRecord::Base; end class LockWithCustomColumnWithoutDefault < ActiveRecord::Base - set_table_name :lock_without_defaults_cust - set_locking_column :custom_lock_version + self.table_name = :lock_without_defaults_cust + self.locking_column = :custom_lock_version end class ReadonlyFirstNamePerson < Person @@ -128,6 +128,24 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_raise(ActiveRecord::StaleObjectError) { p2.save! } end + def test_lock_exception_record + p1 = Person.new(:first_name => 'mira') + assert_equal 0, p1.lock_version + + p1.first_name = 'mira2' + p1.save! + p2 = Person.find(p1.id) + assert_equal 0, p1.lock_version + assert_equal 0, p2.lock_version + + p1.first_name = 'mira3' + p1.save! + + p2.first_name = 'sue' + error = assert_raise(ActiveRecord::StaleObjectError) { p2.save! } + assert_equal(error.record.object_id, p2.object_id) + end + def test_lock_new_with_nil p1 = Person.new(:first_name => 'anika') p1.save! @@ -144,7 +162,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_equal 1, p1.lock_version end - def test_lock_column_name_existing t1 = LegacyThing.find(1) t2 = LegacyThing.find(1) @@ -273,6 +290,8 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase assert_equal true, p1.frozen? assert_raises(ActiveRecord::RecordNotFound) { Person.find(p1.id) } assert_raises(ActiveRecord::RecordNotFound) { LegacyThing.find(t.id) } + ensure + remove_counter_column_from(Person, 'legacy_things_count') end private @@ -284,8 +303,8 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase model.update_all(col => 0) if current_adapter?(:OpenBaseAdapter) end - def remove_counter_column_from(model) - model.connection.remove_column model.table_name, :test_count + def remove_counter_column_from(model, col = :test_count) + model.connection.remove_column model.table_name, col model.reset_column_information end @@ -372,16 +391,6 @@ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db? assert first.end > second.end end - # Hit by ruby deadlock detection since connection checkout is mutexed. - if RUBY_VERSION < '1.9.0' - def test_second_lock_waits - assert [0.2, 1, 5].any? { |zzz| - first, second = duel(zzz) { Person.find 1, :lock => true } - second.end > first.end - } - end - end - protected def duel(zzz = 5) t0, t1, t2, t3 = nil, nil, nil, nil diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb index 9e8475465e..d1f0ace184 100644 --- a/activerecord/test/cases/log_subscriber_test.rb +++ b/activerecord/test/cases/log_subscriber_test.rb @@ -5,7 +5,7 @@ require "active_support/log_subscriber/test_helper" class LogSubscriberTest < ActiveRecord::TestCase include ActiveSupport::LogSubscriber::TestHelper - include ActiveSupport::BufferedLogger::Severity + include ActiveSupport::Logger::Severity fixtures :posts @@ -13,6 +13,7 @@ class LogSubscriberTest < ActiveRecord::TestCase @old_logger = ActiveRecord::Base.logger @using_identity_map = ActiveRecord::IdentityMap.enabled? ActiveRecord::IdentityMap.enabled = false + Developer.primary_key super ActiveRecord::LogSubscriber.attach_to(:active_record) end diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb index ef35f3341e..8122857f52 100644 --- a/activerecord/test/cases/mass_assignment_security_test.rb +++ b/activerecord/test/cases/mass_assignment_security_test.rb @@ -50,6 +50,13 @@ module MassAssignmentTestHelpers assert_equal 'm', person.gender assert_equal 'rides a sweet bike', person.comments end + + def with_strict_sanitizer + ActiveRecord::Base.mass_assignment_sanitizer = :strict + yield + ensure + ActiveRecord::Base.mass_assignment_sanitizer = :logger + end end module MassAssignmentRelationTestHelpers @@ -231,7 +238,9 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase def test_protection_against_class_attribute_writers [:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names, - :default_timezone, :schema_format, :lock_optimistically, :record_timestamps].each do |method| + :default_timezone, :schema_format, :lock_optimistically, :timestamped_migrations, :default_scopes, + :connection_handler, :nested_attributes_options, :_attr_readonly, :attribute_types_cached_by_default, + :attribute_method_matchers, :time_zone_aware_attributes, :skip_time_zone_conversion_for_attributes].each do |method| assert_respond_to Task, method assert_respond_to Task, "#{method}=" assert_respond_to Task.new, method @@ -321,6 +330,13 @@ class MassAssignmentSecurityHasOneRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_one_build_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.build_best_friend(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create def test_has_one_create_with_attr_protected_attributes @@ -348,6 +364,13 @@ class MassAssignmentSecurityHasOneRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_one_create_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create! def test_has_one_create_with_bang_with_attr_protected_attributes @@ -375,6 +398,13 @@ class MassAssignmentSecurityHasOneRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_one_create_with_bang_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend!(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + end @@ -436,6 +466,13 @@ class MassAssignmentSecurityBelongsToRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_belongs_to_create_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend_of(attributes_hash.except(:id, :comments)) + assert_equal best_friend.id, @person.best_friend_of_id + end + end + # create! def test_belongs_to_create_with_bang_with_attr_protected_attributes @@ -463,6 +500,13 @@ class MassAssignmentSecurityBelongsToRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_belongs_to_create_with_bang_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.create_best_friend_of!(attributes_hash.except(:id, :comments)) + assert_equal best_friend.id, @person.best_friend_of_id + end + end + end @@ -497,6 +541,13 @@ class MassAssignmentSecurityHasManyRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_many_build_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.best_friends.build(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create def test_has_many_create_with_attr_protected_attributes @@ -524,6 +575,13 @@ class MassAssignmentSecurityHasManyRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_many_create_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.best_friends.create(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + # create! def test_has_many_create_with_bang_with_attr_protected_attributes @@ -551,6 +609,13 @@ class MassAssignmentSecurityHasManyRelationsTest < ActiveRecord::TestCase assert_all_attributes(best_friend) end + def test_has_many_create_with_bang_with_strict_sanitizer + with_strict_sanitizer do + best_friend = @person.best_friends.create!(attributes_hash.except(:id, :comments)) + assert_equal @person.id, best_friend.best_friend_id + end + end + end diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 0ab4f30363..0f0621f2e0 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -103,7 +103,7 @@ class MethodScopingTest < ActiveRecord::TestCase def test_scoped_find_include # with the include, will retrieve only developers for the given project - scoped_developers = Developer.send(:with_scope, :find => { :include => :projects }) do + scoped_developers = Developer.send(:with_scope, :find => { :eager_load => :projects }) do Developer.find(:all, :conditions => 'projects.id = 2') end assert scoped_developers.include?(developers(:david)) @@ -203,7 +203,7 @@ class MethodScopingTest < ActiveRecord::TestCase def test_scoped_count_include # with the include, will retrieve only developers for the given project - Developer.send(:with_scope, :find => { :include => :projects }) do + Developer.send(:with_scope, :find => { :eager_load => :projects }) do assert_equal 1, Developer.count(:conditions => 'projects.id = 2') end end @@ -268,7 +268,7 @@ class MethodScopingTest < ActiveRecord::TestCase end class NestedScopingTest < ActiveRecord::TestCase - fixtures :authors, :developers, :projects, :comments, :posts + fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects def test_merge_options Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do @@ -338,7 +338,7 @@ class NestedScopingTest < ActiveRecord::TestCase end def test_nested_scoped_find_include - Developer.send(:with_scope, :find => { :include => :projects }) do + Developer.send(:with_scope, :find => { :eager_load => :projects }) do Developer.send(:with_scope, :find => { :conditions => "projects.id = 2" }) do assert_nothing_raised { Developer.find(1) } assert_equal('David', Developer.find(:first).name) @@ -350,23 +350,47 @@ class NestedScopingTest < ActiveRecord::TestCase # :include's remain unique and don't "double up" when merging Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do Developer.send(:with_scope, :find => { :include => :projects }) do - assert_equal 1, Developer.scoped.includes_values.uniq.length - assert_equal 'David', Developer.find(:first).name + assert_deprecated do + assert_equal 1, Developer.scoped.includes_values.uniq.length + assert_equal 'David', Developer.find(:first).name + end end end # the nested scope doesn't remove the first :include Developer.send(:with_scope, :find => { :include => :projects, :conditions => "projects.id = 2" }) do Developer.send(:with_scope, :find => { :include => [] }) do - assert_equal 1, Developer.scoped.includes_values.uniq.length - assert_equal('David', Developer.find(:first).name) + assert_deprecated do + assert_equal 1, Developer.scoped.includes_values.uniq.length + assert_equal('David', Developer.find(:first).name) + end end end # mixing array and symbol include's will merge correctly Developer.send(:with_scope, :find => { :include => [:projects], :conditions => "projects.id = 2" }) do Developer.send(:with_scope, :find => { :include => :projects }) do - assert_equal 1, Developer.scoped.includes_values.uniq.length + assert_deprecated do + assert_equal 1, Developer.scoped.includes_values.uniq.length + assert_equal('David', Developer.find(:first).name) + end + end + end + end + + def test_nested_scoped_find_merged_eager_load + # :include's remain unique and don't "double up" when merging + Developer.send(:with_scope, :find => { :eager_load => :projects, :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :eager_load => :projects }) do + assert_equal 1, Developer.scoped.eager_load_values.uniq.length + assert_equal 'David', Developer.find(:first).name + end + end + + # mixing array and symbol include's will merge correctly + Developer.send(:with_scope, :find => { :eager_load => [:projects], :conditions => "projects.id = 2" }) do + Developer.send(:with_scope, :find => { :eager_load => :projects }) do + assert_equal 1, Developer.scoped.eager_load_values.uniq.length assert_equal('David', Developer.find(:first).name) end end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 93a1249e43..1e68911ab3 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -6,6 +6,8 @@ require 'models/topic' require 'models/developer' require MIGRATIONS_ROOT + "/valid/2_we_need_reminders" +require MIGRATIONS_ROOT + "/rename/1_we_need_things" +require MIGRATIONS_ROOT + "/rename/2_rename_things" require MIGRATIONS_ROOT + "/decimal/1_give_me_big_numbers" if ActiveRecord::Base.connection.supports_migrations? @@ -13,6 +15,8 @@ if ActiveRecord::Base.connection.supports_migrations? class Reminder < ActiveRecord::Base; end + class Thing < ActiveRecord::Base; end + class ActiveRecord::Migration class << self attr_accessor :message_count @@ -57,6 +61,11 @@ if ActiveRecord::Base.connection.supports_migrations? ActiveRecord::Base.connection.initialize_schema_migrations_table ActiveRecord::Base.connection.execute "DELETE FROM #{ActiveRecord::Migrator.schema_migrations_table_name}" + %w(things awesome_things prefix_things_suffix prefix_awesome_things_suffix).each do |table| + Thing.connection.drop_table(table) rescue nil + end + Thing.reset_column_information + %w(reminders people_reminders prefix_reminders_suffix).each do |table| Reminder.connection.drop_table(table) rescue nil end @@ -121,6 +130,18 @@ if ActiveRecord::Base.connection.supports_migrations? assert_nothing_raised { Person.connection.add_index("people", %w(last_name first_name administrator), :name => "named_admin") } assert_nothing_raised { Person.connection.remove_index("people", :name => "named_admin") } end + + # Selected adapters support index sort order + if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter) + assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :order => {:last_name => :desc}) } + assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) } + assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc}) } + assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } + assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc}) } + assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } + assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => :desc) } + assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) } + end end def test_index_symbol_names @@ -389,8 +410,8 @@ if ActiveRecord::Base.connection.supports_migrations? created_at_column = created_columns.detect {|c| c.name == 'created_at' } updated_at_column = created_columns.detect {|c| c.name == 'updated_at' } - assert created_at_column.null - assert updated_at_column.null + assert !created_at_column.null + assert !updated_at_column.null ensure Person.connection.drop_table table_name rescue nil end @@ -471,11 +492,13 @@ if ActiveRecord::Base.connection.supports_migrations? # Do a manual insertion if current_adapter?(:OracleAdapter) - Person.connection.execute "insert into people (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)" + Person.connection.execute "insert into people (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)" elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings - Person.connection.execute "insert into people (wealth) values ('12345678901234567890.0123456789')" + Person.connection.execute "insert into people (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)" + elsif current_adapter?(:PostgreSQLAdapter) + Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())" else - Person.connection.execute "insert into people (wealth) values (12345678901234567890.0123456789)" + Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)" end # SELECT @@ -516,6 +539,42 @@ if ActiveRecord::Base.connection.supports_migrations? assert_equal 7, wealth_column.scale end + # Test SQLite adapter specifically for decimal types with precision and scale + # attributes, since these need to be maintained in schema but aren't actually + # used in SQLite itself + if current_adapter?(:SQLite3Adapter) + def test_change_column_with_new_precision_and_scale + Person.delete_all + Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7 + Person.reset_column_information + + Person.connection.change_column 'people', 'wealth', :decimal, :precision => 12, :scale => 8 + Person.reset_column_information + + wealth_column = Person.columns_hash['wealth'] + assert_equal 12, wealth_column.precision + assert_equal 8, wealth_column.scale + end + + def test_change_column_preserve_other_column_precision_and_scale + Person.delete_all + Person.connection.add_column 'people', 'last_name', :string + Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7 + Person.reset_column_information + + wealth_column = Person.columns_hash['wealth'] + assert_equal 9, wealth_column.precision + assert_equal 7, wealth_column.scale + + Person.connection.change_column 'people', 'last_name', :string, :null => false + Person.reset_column_information + + wealth_column = Person.columns_hash['wealth'] + assert_equal 9, wealth_column.precision + assert_equal 7, wealth_column.scale + end + end + def test_native_types Person.delete_all Person.connection.add_column "people", "last_name", :string @@ -977,7 +1036,7 @@ if ActiveRecord::Base.connection.supports_migrations? t.column :title, :string end person_klass = Class.new(Person) - person_klass.set_table_name 'testings' + person_klass.table_name = 'testings' person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99 person_klass.reset_column_information @@ -1176,6 +1235,24 @@ if ActiveRecord::Base.connection.supports_migrations? assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } end + def test_filtering_migrations + assert !Person.column_methods_hash.include?(:last_name) + assert !Reminder.table_exists? + + name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" } + ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", &name_filter) + + Person.reset_column_information + assert Person.column_methods_hash.include?(:last_name) + assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } + + ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid", &name_filter) + + Person.reset_column_information + assert !Person.column_methods_hash.include?(:last_name) + assert_raise(ActiveRecord::StatementInvalid) { Reminder.find(:first) } + end + class MockMigration < ActiveRecord::Migration attr_reader :went_up, :went_down def initialize @@ -1287,6 +1364,15 @@ if ActiveRecord::Base.connection.supports_migrations? end end + def test_finds_migrations_in_subdirectories + migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/valid_with_subdirectories").migrations + + [[1, 'ValidPeopleHaveLastNames'], [2, 'WeNeedReminders'], [3, 'InnocentJointable']].each_with_index do |pair, i| + assert_equal migrations[i].version, pair.first + assert_equal migrations[i].name, pair.last + end + end + def test_finds_migrations_from_two_directories directories = [MIGRATIONS_ROOT + '/valid_with_timestamps', MIGRATIONS_ROOT + '/to_copy_with_timestamps'] migrations = ActiveRecord::Migrator.new(:up, directories).migrations @@ -1301,6 +1387,15 @@ if ActiveRecord::Base.connection.supports_migrations? end end + def test_dump_schema_information_outputs_lexically_ordered_versions + migration_path = MIGRATIONS_ROOT + '/valid_with_timestamps' + ActiveRecord::Migrator.run(:up, migration_path, 20100301010101) + ActiveRecord::Migrator.run(:up, migration_path, 20100201010101) + + schema_info = ActiveRecord::Base.connection.dump_schema_information + assert_match(/20100201010101.*20100301010101/m, schema_info) + end + def test_finds_pending_migrations ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2", 1) migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2").pending_migrations @@ -1475,6 +1570,28 @@ if ActiveRecord::Base.connection.supports_migrations? Reminder.reset_table_name end + def test_rename_table_with_prefix_and_suffix + assert !Thing.table_exists? + ActiveRecord::Base.table_name_prefix = 'prefix_' + ActiveRecord::Base.table_name_suffix = '_suffix' + Thing.reset_table_name + Thing.reset_sequence_name + WeNeedThings.up + + assert Thing.create("content" => "hello world") + assert_equal "hello world", Thing.find(:first).content + + RenameThings.up + Thing.table_name = "prefix_awesome_things_suffix" + + assert_equal "hello world", Thing.find(:first).content + ensure + ActiveRecord::Base.table_name_prefix = '' + ActiveRecord::Base.table_name_suffix = '' + Thing.reset_table_name + Thing.reset_sequence_name + end + def test_add_drop_table_with_prefix_and_suffix assert !Reminder.table_exists? ActiveRecord::Base.table_name_prefix = 'prefix_' @@ -1580,91 +1697,6 @@ if ActiveRecord::Base.connection.supports_migrations? end - class SexyMigrationsTest < ActiveRecord::TestCase - def test_references_column_type_adds_id - with_new_table do |t| - t.expects(:column).with('customer_id', :integer, {}) - t.references :customer - end - end - - def test_references_column_type_with_polymorphic_adds_type - with_new_table do |t| - t.expects(:column).with('taggable_type', :string, {}) - t.expects(:column).with('taggable_id', :integer, {}) - t.references :taggable, :polymorphic => true - end - end - - def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag - with_new_table do |t| - t.expects(:column).with('taggable_type', :string, {:null => false}) - t.expects(:column).with('taggable_id', :integer, {:null => false}) - t.references :taggable, :polymorphic => true, :null => false - end - end - - def test_belongs_to_works_like_references - with_new_table do |t| - t.expects(:column).with('customer_id', :integer, {}) - t.belongs_to :customer - end - end - - def test_timestamps_creates_updated_at_and_created_at - with_new_table do |t| - t.expects(:column).with(:created_at, :datetime, kind_of(Hash)) - t.expects(:column).with(:updated_at, :datetime, kind_of(Hash)) - t.timestamps - end - end - - def test_integer_creates_integer_column - with_new_table do |t| - t.expects(:column).with(:foo, 'integer', {}) - t.expects(:column).with(:bar, 'integer', {}) - t.integer :foo, :bar - end - end - - def test_string_creates_string_column - with_new_table do |t| - t.expects(:column).with(:foo, 'string', {}) - t.expects(:column).with(:bar, 'string', {}) - t.string :foo, :bar - end - end - - if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLite3Adapter) || current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter) - def test_xml_creates_xml_column - type = current_adapter?(:PostgreSQLAdapter) ? 'xml' : :text - - with_new_table do |t| - t.expects(:column).with(:data, type, {}) - t.xml :data - end - end - else - def test_xml_creates_xml_column - with_new_table do |t| - assert_raises(NotImplementedError) do - t.xml :data - end - end - end - end - - protected - def with_new_table - Person.connection.create_table :delete_me, :force => true do |t| - yield t - end - ensure - Person.connection.drop_table :delete_me rescue nil - end - - end # SexyMigrationsTest - class MigrationLoggerTest < ActiveRecord::TestCase def test_migration_should_be_run_without_logger previous_logger = ActiveRecord::Base.logger @@ -2094,9 +2126,12 @@ if ActiveRecord::Base.connection.supports_migrations? @existing_migrations = Dir[@migrations_path + "/*.rb"] copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) - assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb") - assert_equal [@migrations_path + "/4_people_have_hobbies.rb", @migrations_path + "/5_people_have_descriptions.rb"], copied.map(&:filename) + assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") + assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename) + + expected = "# This migration comes from bukkits (originally 1)" + assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp files_count = Dir[@migrations_path + "/*.rb"].length copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"}) @@ -2115,10 +2150,10 @@ if ActiveRecord::Base.connection.supports_migrations? sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy" sources[:omg] = MIGRATIONS_ROOT + "/to_copy2" ActiveRecord::Migration.copy(@migrations_path, sources) - assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb") - assert File.exists?(@migrations_path + "/6_create_articles.rb") - assert File.exists?(@migrations_path + "/7_create_comments.rb") + assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb") + assert File.exists?(@migrations_path + "/6_create_articles.omg.rb") + assert File.exists?(@migrations_path + "/7_create_comments.omg.rb") files_count = Dir[@migrations_path + "/*.rb"].length ActiveRecord::Migration.copy(@migrations_path, sources) @@ -2133,10 +2168,10 @@ if ActiveRecord::Base.connection.supports_migrations? Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") - expected = [@migrations_path + "/20100726101010_people_have_hobbies.rb", - @migrations_path + "/20100726101011_people_have_descriptions.rb"] + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") + expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb", + @migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"] assert_equal expected, copied.map(&:filename) files_count = Dir[@migrations_path + "/*.rb"].length @@ -2158,10 +2193,10 @@ if ActiveRecord::Base.connection.supports_migrations? Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do copied = ActiveRecord::Migration.copy(@migrations_path, sources) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") - assert File.exists?(@migrations_path + "/20100726101012_create_articles.rb") - assert File.exists?(@migrations_path + "/20100726101013_create_comments.rb") + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101012_create_articles.omg.rb") + assert File.exists?(@migrations_path + "/20100726101013_create_comments.omg.rb") assert_equal 4, copied.length files_count = Dir[@migrations_path + "/*.rb"].length @@ -2178,8 +2213,8 @@ if ActiveRecord::Base.connection.supports_migrations? Time.travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.rb") + assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb") files_count = Dir[@migrations_path + "/*.rb"].length copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) @@ -2195,15 +2230,34 @@ if ActiveRecord::Base.connection.supports_migrations? @existing_migrations = Dir[@migrations_path + "/*.rb"] sources = ActiveSupport::OrderedHash.new - sources[:bukkits] = sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" + sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" + sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_name_collision" skipped = [] on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) assert_equal 2, copied.length - assert_equal 2, skipped.length - assert_equal ["bukkits PeopleHaveHobbies", "bukkits PeopleHaveDescriptions"], skipped + assert_equal 1, skipped.length + assert_equal ["omg PeopleHaveHobbies"], skipped + ensure + clear + end + + def test_skip_is_not_called_if_migrations_are_from_the_same_plugin + @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps" + @existing_migrations = Dir[@migrations_path + "/*.rb"] + + sources = ActiveSupport::OrderedHash.new + sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps" + + skipped = [] + on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" } + copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip) + + assert_equal 2, copied.length + assert_equal 0, skipped.length ensure clear end @@ -2214,8 +2268,8 @@ if ActiveRecord::Base.connection.supports_migrations? Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert_equal 2, copied.length end ensure @@ -2229,8 +2283,8 @@ if ActiveRecord::Base.connection.supports_migrations? Time.travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"}) - assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb") - assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb") + assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb") + assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb") assert_equal 2, copied.length end ensure diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index a2041af16a..72d96f2bab 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -72,7 +72,7 @@ class ModulesTest < ActiveRecord::TestCase clients = [] assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do - clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL') + clients << MyApplication::Business::Client.find(3, :eager_load => {:firm => :account}, :conditions => 'accounts.id IS NOT NULL') clients << MyApplication::Business::Client.find(3, :include => {:firm => :account}) end diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index bd51388e05..e704322b5d 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -85,7 +85,6 @@ class MultipleDbTest < ActiveRecord::TestCase end def test_arel_table_engines - assert_not_equal Entrant.arel_engine, Course.arel_engine assert_equal Entrant.arel_engine, Bird.arel_engine end end diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 4a09a87322..e17ba76437 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -1,5 +1,4 @@ require "cases/helper" -require 'active_support/core_ext/array/random_access' require 'models/post' require 'models/topic' require 'models/comment' @@ -337,6 +336,11 @@ class NamedScopeTest < ActiveRecord::TestCase end end + def test_should_not_duplicates_where_values + where_values = Topic.where("1=1").scope_with_lambda.where_values + assert_equal ["1=1"], where_values + end + def test_chaining_with_duplicate_joins join = "INNER JOIN comments ON comments.post_id = posts.id" post = Post.find(1) diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 67a9ed6cd8..2ae9cb4888 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -45,6 +45,14 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase end end + def test_should_not_build_a_new_record_using_reject_all_even_if_destroy_is_given + pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") + pirate.birds_with_reject_all_blank_attributes = [{:name => '', :color => '', :_destroy => '0'}] + pirate.save! + + assert pirate.birds_with_reject_all_blank.empty? + end + def test_should_not_build_a_new_record_if_reject_all_blank_returns_false pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") pirate.birds_with_reject_all_blank_attributes = [{:name => '', :color => ''}] diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 379cf5b44e..fba3006ebe 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -3,19 +3,21 @@ require "models/project" require "timeout" class PooledConnectionsTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + def setup @per_test_teardown = [] - @connection = ActiveRecord::Base.remove_connection + @connection = ActiveRecord::Model.remove_connection end def teardown - ActiveRecord::Base.clear_all_connections! - ActiveRecord::Base.establish_connection(@connection) + ActiveRecord::Model.clear_all_connections! + ActiveRecord::Model.establish_connection(@connection) @per_test_teardown.each {|td| td.call } end def checkout_connections - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3})) + ActiveRecord::Model.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3})) @connections = [] @timed_out = 0 @@ -31,24 +33,16 @@ class PooledConnectionsTest < ActiveRecord::TestCase end # Will deadlock due to lack of Monitor timeouts in 1.9 - if RUBY_VERSION < '1.9' - def test_pooled_connection_checkout - checkout_connections - assert_equal 2, @connections.length - assert_equal 2, @timed_out - end - end - def checkout_checkin_connections(pool_size, threads) - ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5})) + ActiveRecord::Model.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5})) @connection_count = 0 @timed_out = 0 threads.times do Thread.new do begin - conn = ActiveRecord::Base.connection_pool.checkout + conn = ActiveRecord::Model.connection_pool.checkout sleep 0.1 - ActiveRecord::Base.connection_pool.checkin conn + ActiveRecord::Model.connection_pool.checkin conn @connection_count += 1 rescue ActiveRecord::ConnectionTimeoutError @timed_out += 1 @@ -61,85 +55,13 @@ class PooledConnectionsTest < ActiveRecord::TestCase checkout_checkin_connections 1, 2 assert_equal 2, @connection_count assert_equal 0, @timed_out - assert_equal 1, ActiveRecord::Base.connection_pool.connections.size - end - - def test_pooled_connection_checkin_two - checkout_checkin_connections 2, 3 - assert_equal 3, @connection_count - assert_equal 0, @timed_out - assert_equal 1, ActiveRecord::Base.connection_pool.connections.size - end - - def test_pooled_connection_checkout_existing_first - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1})) - conn_pool = ActiveRecord::Base.connection_pool - conn = conn_pool.checkout - conn_pool.checkin(conn) - conn = conn_pool.checkout - assert ActiveRecord::ConnectionAdapters::AbstractAdapter === conn - conn_pool.checkin(conn) - end - - def test_not_connected_defined_connection_returns_false - ActiveRecord::Base.establish_connection(@connection) - assert ! ActiveRecord::Base.connected? - end - - def test_undefined_connection_returns_false - old_handler = ActiveRecord::Base.connection_handler - ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new - assert ! ActiveRecord::Base.connected? - ensure - ActiveRecord::Base.connection_handler = old_handler + assert_equal 1, ActiveRecord::Model.connection_pool.connections.size end - def test_connection_config - ActiveRecord::Base.establish_connection(@connection) - assert_equal @connection, ActiveRecord::Base.connection_config - end - - def test_with_connection_nesting_safety - ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1, :wait_timeout => 0.1})) - - before_count = Project.count - - add_record('one') - - ActiveRecord::Base.connection.transaction do - add_record('two') - # Have another thread try to screw up the transaction - Thread.new do - ActiveRecord::Base.connection.rollback_db_transaction - ActiveRecord::Base.connection_pool.release_connection - end - add_record('three') - end - - after_count = Project.count - assert_equal 3, after_count - before_count - end - - def test_connection_pool_callbacks - checked_out, checked_in = false, false - ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do - set_callback(:checkout, :after) { checked_out = true } - set_callback(:checkin, :before) { checked_in = true } - end - @per_test_teardown << proc do - ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do - reset_callbacks :checkout - reset_callbacks :checkin - end - end - checkout_checkin_connections 1, 1 - assert checked_out - assert checked_in - end private def add_record(name) - ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name } + ActiveRecord::Model.connection_pool.with_connection { Project.create! :name => name } end end unless current_adapter?(:FrontBase) || in_memory_db? diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb index 58badd6266..b4d1a631fa 100644 --- a/activerecord/test/cases/primary_keys_test.rb +++ b/activerecord/test/cases/primary_keys_test.rb @@ -5,7 +5,6 @@ require 'models/subscriber' require 'models/movie' require 'models/keyboard' require 'models/mixed_case_monkey' -require 'models/edge' class PrimaryKeysTest < ActiveRecord::TestCase fixtures :topics, :subscribers, :movies, :mixed_case_monkeys @@ -24,6 +23,11 @@ class PrimaryKeysTest < ActiveRecord::TestCase assert_equal keyboard.to_key, [keyboard.id] end + def test_read_attribute_with_custom_primary_key + keyboard = Keyboard.create! + assert_equal keyboard.key_number, keyboard.read_attribute(:id) + end + def test_to_key_with_primary_key_after_destroy topic = Topic.find(1) topic.destroy @@ -143,36 +147,56 @@ class PrimaryKeysTest < ActiveRecord::TestCase assert_equal k.connection.quote_column_name("id"), k.quoted_primary_key k.primary_key = "foo" assert_equal k.connection.quote_column_name("foo"), k.quoted_primary_key - k.set_primary_key "bar" - assert_equal k.connection.quote_column_name("bar"), k.quoted_primary_key end - def test_set_primary_key_with_no_connection - return skip("disconnect wipes in-memory db") if in_memory_db? + def test_two_models_with_same_table_but_different_primary_key + k1 = Class.new(ActiveRecord::Base) + k1.table_name = 'posts' + k1.primary_key = 'id' + + k2 = Class.new(ActiveRecord::Base) + k2.table_name = 'posts' + k2.primary_key = 'title' - connection = ActiveRecord::Base.remove_connection + assert k1.columns.find { |c| c.name == 'id' }.primary + assert !k1.columns.find { |c| c.name == 'title' }.primary + assert k1.columns_hash['id'].primary + assert !k1.columns_hash['title'].primary - model = Class.new(ActiveRecord::Base) do - set_primary_key 'foo' + assert !k2.columns.find { |c| c.name == 'id' }.primary + assert k2.columns.find { |c| c.name == 'title' }.primary + assert !k2.columns_hash['id'].primary + assert k2.columns_hash['title'].primary + end + + def test_models_with_same_table_have_different_columns + k1 = Class.new(ActiveRecord::Base) + k1.table_name = 'posts' + + k2 = Class.new(ActiveRecord::Base) + k2.table_name = 'posts' + + k1.columns.zip(k2.columns).each do |col1, col2| + assert !col1.equal?(col2) end + end +end - assert_equal 'foo', model.primary_key +class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false + + def test_set_primary_key_with_no_connection + return skip("disconnect wipes in-memory db") if in_memory_db? - ActiveRecord::Base.establish_connection(connection) + connection = ActiveRecord::Model.remove_connection + + model = Class.new(ActiveRecord::Base) + model.primary_key = 'foo' assert_equal 'foo', model.primary_key - end - def test_no_primary_key_raises - assert_raises(ActiveRecord::UnknownPrimaryKey) do - Edge.primary_key - end + ActiveRecord::Model.establish_connection(connection) - begin - Edge.primary_key - rescue ActiveRecord::UnknownPrimaryKey => e - assert e.message.include?('edges') - assert e.message.include?('Edge') - end + assert_equal 'foo', model.primary_key end end diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index 7feac2b920..9554386dcf 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -170,6 +170,18 @@ end class QueryCacheExpiryTest < ActiveRecord::TestCase fixtures :tasks, :posts, :categories, :categories_posts + def test_cache_gets_cleared_after_migration + # warm the cache + Post.find(1) + + # change the column definition + Post.connection.change_column :posts, :title, :string, :limit => 80 + assert_nothing_raised { Post.find(1) } + + # restore the old definition + Post.connection.change_column :posts, :title, :string + end + def test_find Task.connection.expects(:clear_query_cache).times(1) @@ -237,7 +249,7 @@ class QueryCacheBodyProxyTest < ActiveRecord::TestCase test "is polite to it's body and responds to it" do body = Class.new(String) { def to_path; "/path"; end }.new - proxy = ActiveRecord::QueryCache::BodyProxy.new(nil, body) + proxy = ActiveRecord::QueryCache::BodyProxy.new(nil, body, ActiveRecord::Base.connection_id) assert proxy.respond_to?(:to_path) assert_equal proxy.to_path, "/path" end diff --git a/activerecord/test/cases/reaper_test.rb b/activerecord/test/cases/reaper_test.rb new file mode 100644 index 0000000000..576ab60090 --- /dev/null +++ b/activerecord/test/cases/reaper_test.rb @@ -0,0 +1,81 @@ +require "cases/helper" + +module ActiveRecord + module ConnectionAdapters + class ReaperTest < ActiveRecord::TestCase + attr_reader :pool + + def setup + super + @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec + end + + def teardown + super + @pool.connections.each(&:close) + end + + class FakePool + attr_reader :reaped + + def initialize + @reaped = false + end + + def reap + @reaped = true + end + end + + # A reaper with nil time should never reap connections + def test_nil_time + fp = FakePool.new + assert !fp.reaped + reaper = ConnectionPool::Reaper.new(fp, nil) + reaper.run + assert !fp.reaped + end + + def test_some_time + fp = FakePool.new + assert !fp.reaped + + reaper = ConnectionPool::Reaper.new(fp, 0.0001) + reaper.run + until fp.reaped + Thread.pass + end + assert fp.reaped + end + + def test_pool_has_reaper + assert pool.reaper + end + + def test_reaping_frequency_configuration + spec = ActiveRecord::Base.connection_pool.spec.dup + spec.config[:reaping_frequency] = 100 + pool = ConnectionPool.new spec + assert_equal 100, pool.reaper.frequency + end + + def test_connection_pool_starts_reaper + spec = ActiveRecord::Base.connection_pool.spec.dup + spec.config[:reaping_frequency] = 0.0001 + + pool = ConnectionPool.new spec + pool.timeout = 0 + + conn = pool.checkout + count = pool.connections.length + + conn.extend(Module.new { def active?; false; end; }) + + while count == pool.connections.length + Thread.pass + end + assert_equal(count - 1, pool.connections.length) + end + end + end +end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index ca9d88fbd5..7fd15027eb 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -18,6 +18,7 @@ require 'models/subscriber' require 'models/subscription' require 'models/tag' require 'models/sponsor' +require 'models/edge' class ReflectionTest < ActiveRecord::TestCase include ActiveRecord::Reflection @@ -35,25 +36,25 @@ class ReflectionTest < ActiveRecord::TestCase def test_read_attribute_names assert_equal( - %w( id title author_name author_email_address bonus_time written_on last_read content group approved replies_count parent_id parent_title type created_at updated_at ).sort, + %w( id title author_name author_email_address bonus_time written_on last_read content important group approved replies_count parent_id parent_title type created_at updated_at ).sort, @first.attribute_names.sort ) end def test_columns - assert_equal 16, Topic.columns.length + assert_equal 17, Topic.columns.length end def test_columns_are_returned_in_the_order_they_were_declared column_names = Topic.columns.map { |column| column.name } - assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content approved replies_count parent_id parent_title type group created_at updated_at), column_names + assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content important approved replies_count parent_id parent_title type group created_at updated_at), column_names end def test_content_columns content_columns = Topic.content_columns content_column_names = content_columns.map {|column| column.name} - assert_equal 12, content_columns.length - assert_equal %w(title author_name author_email_address written_on bonus_time last_read content group approved parent_title created_at updated_at).sort, content_column_names.sort + assert_equal 13, content_columns.length + assert_equal %w(title author_name author_email_address written_on bonus_time last_read content important group approved parent_title created_at updated_at).sort, content_column_names.sort end def test_column_string_type_and_limit @@ -188,8 +189,8 @@ class ReflectionTest < ActiveRecord::TestCase def test_reflection_of_all_associations # FIXME these assertions bust a lot - assert_equal 36, Firm.reflect_on_all_associations.size - assert_equal 26, Firm.reflect_on_all_associations(:has_many).size + assert_equal 37, Firm.reflect_on_all_associations.size + assert_equal 27, Firm.reflect_on_all_associations(:has_many).size assert_equal 10, Firm.reflect_on_all_associations(:has_one).size assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size end @@ -252,11 +253,25 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal "custom_primary_key", Author.reflect_on_association(:tags_with_primary_key).association_primary_key.to_s # nested end + def test_association_primary_key_raises_when_missing_primary_key + reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, {}, Author) + assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.association_primary_key } + + through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, {}, Author) + through.stubs(:source_reflection).returns(stub_everything(:options => {}, :class_name => 'Edge')) + assert_raises(ActiveRecord::UnknownPrimaryKey) { through.association_primary_key } + end + def test_active_record_primary_key assert_equal "nick", Subscriber.reflect_on_association(:subscriptions).active_record_primary_key.to_s assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s end + def test_active_record_primary_key_raises_when_missing_primary_key + reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, {}, Edge) + assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.active_record_primary_key } + end + def test_foreign_type assert_equal "sponsorable_type", Sponsor.reflect_on_association(:sponsorable).foreign_type.to_s assert_equal "sponsorable_type", Sponsor.reflect_on_association(:thing).foreign_type.to_s @@ -304,6 +319,16 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s end + def test_through_reflection_conditions_do_not_modify_other_reflections + orig_conds = Post.reflect_on_association(:first_blue_tags_2).conditions.inspect + Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions + assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).conditions.inspect + end + + def test_symbol_for_class_name + assert_equal Client, Firm.reflect_on_association(:unsorted_clients_with_symbol).klass + end + private def assert_reflection(klass, association, options) assert reflection = klass.reflect_on_association(association) diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 1e2093273e..8b4638b161 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -105,7 +105,7 @@ class RelationScopingTest < ActiveRecord::TestCase def test_scoped_find_include # with the include, will retrieve only developers for the given project - scoped_developers = Developer.includes(:projects).scoping do + scoped_developers = Developer.eager_load(:projects).scoping do Developer.where('projects.id = 2').all end assert scoped_developers.include?(developers(:david)) @@ -522,12 +522,12 @@ class DefaultScopingTest < ActiveRecord::TestCase d = DeveloperWithIncludes.create! d.audit_logs.create! :message => 'foo' - assert_equal 1, DeveloperWithIncludes.where(:audit_logs => { :message => 'foo' }).count + assert_equal 1, DeveloperWithIncludes.eager_load(:audit_logs).where(:audit_logs => { :message => 'foo' }).count end def test_default_scope_is_threadsafe if in_memory_db? - skip "in memory db can't share a db between threads" + return skip "in memory db can't share a db between threads" end threads = [] diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index b23ead6feb..15cb7aec07 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -20,7 +20,7 @@ module ActiveRecord end def test_single_values - assert_equal [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order].map(&:to_s).sort, + assert_equal [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order, :uniq].map(&:to_s).sort, Relation::SINGLE_VALUE_METHODS.map(&:to_s).sort end @@ -135,5 +135,11 @@ module ActiveRecord relation.eager_load_values << :b assert relation.eager_loading? end + + def test_apply_finder_options_supports_eager_load + relation = Relation.new :a, :b + relation = relation.apply_finder_options(:eager_load => :b) + assert_equal [:b], relation.eager_load_values + end end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 95408a5f29..f1a9f3e0a1 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -16,7 +16,6 @@ require 'models/engine' require 'models/tyre' require 'models/minivan' - class RelationTest < ActiveRecord::TestCase fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments, :tags, :taggings, :cars, :minivans @@ -177,19 +176,19 @@ class RelationTest < ActiveRecord::TestCase end def test_finding_with_cross_table_order_and_limit - tags = Tag.includes(:taggings). + tags = Tag.eager_load(:taggings). order("tags.name asc", "taggings.taggable_id asc", "REPLACE('abc', taggings.taggable_type, taggings.taggable_type)"). limit(1).to_a assert_equal 1, tags.length end def test_finding_with_complex_order_and_limit - tags = Tag.includes(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a + tags = Tag.eager_load(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").limit(1).to_a assert_equal 1, tags.length end def test_finding_with_complex_order - tags = Tag.includes(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a + tags = Tag.eager_load(:taggings).order("REPLACE('abc', taggings.taggable_type, taggings.taggable_type)").to_a assert_equal 3, tags.length end @@ -1104,7 +1103,9 @@ class RelationTest < ActiveRecord::TestCase ) ) - assert scope.eager_loading? + assert_deprecated do + assert scope.eager_loading? + end end def test_ordering_with_extra_spaces @@ -1148,4 +1149,35 @@ class RelationTest < ActiveRecord::TestCase assert_equal posts(:thinking), comments(:more_greetings).post assert_equal posts(:welcome), comments(:greetings).post end + + def test_uniq + tag1 = Tag.create(:name => 'Foo') + tag2 = Tag.create(:name => 'Foo') + + query = Tag.select(:name).where(:id => [tag1.id, tag2.id]) + + assert_equal ['Foo', 'Foo'], query.map(&:name) + assert_sql(/DISTINCT/) do + assert_equal ['Foo'], query.uniq.map(&:name) + end + assert_sql(/DISTINCT/) do + assert_equal ['Foo'], query.uniq(true).map(&:name) + end + assert_equal ['Foo', 'Foo'], query.uniq(true).uniq(false).map(&:name) + end + + def test_deprecated_references_eager_loaded_tables + expected = tags(:general) + tagging = taggings(:welcome_general) + tag = assert_queries 1 do + assert_deprecated do + Tag.includes(:taggings).where(:taggings => { :id => tagging.id }).to_a.first + end + end + + assert_equal expected, tag + assert_no_queries do + tag.taggings.to_a + end + end end diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 71ff727b7f..dd6d7e52d5 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -13,10 +13,8 @@ class SchemaDumperTest < ActiveRecord::TestCase @stream.string end - if "string".encoding_aware? - def test_magic_comment - assert_match "# encoding: #{@stream.external_encoding.name}", standard_dump - end + def test_magic_comment + assert_match "# encoding: #{@stream.external_encoding.name}", standard_dump end def test_schema_dump @@ -238,4 +236,9 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_match %r(:id => false), match[1], "no table id not preserved" assert_match %r{t.string[[:space:]]+"id",[[:space:]]+:null => false$}, match[2], "non-primary key id column not preserved" end + + def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_added + output = standard_dump + assert_match %r{create_table "subscribers", :id => false}, output + end end diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb index 258cee7aba..bcacbb9b5f 100644 --- a/activerecord/test/cases/session_store/session_test.rb +++ b/activerecord/test/cases/session_store/session_test.rb @@ -5,10 +5,11 @@ require 'active_record/session_store' module ActiveRecord class SessionStore class SessionTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? && ActiveRecord::Base.connection.supports_ddl_transactions? + self.use_transactional_fixtures = false def setup super + ActiveRecord::Base.connection.schema_cache.clear! Session.drop_table! if Session.table_exists? end diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb new file mode 100644 index 0000000000..5a3f9a9711 --- /dev/null +++ b/activerecord/test/cases/store_test.rb @@ -0,0 +1,34 @@ +require 'cases/helper' +require 'models/admin' +require 'models/admin/user' + +class StoreTest < ActiveRecord::TestCase + setup do + @john = Admin::User.create(:name => 'John Doe', :color => 'black') + end + + test "reading store attributes through accessors" do + assert_equal 'black', @john.color + assert_nil @john.homepage + end + + test "writing store attributes through accessors" do + @john.color = 'red' + @john.homepage = '37signals.com' + + assert_equal 'red', @john.color + assert_equal '37signals.com', @john.homepage + end + + test "accessing attributes not exposed by accessors" do + @john.settings[:icecream] = 'graeters' + @john.save + + assert_equal 'graeters', @john.reload.settings[:icecream] + end + + test "updating the store will mark it as changed" do + @john.color = 'red' + assert @john.settings_changed? + end +end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 4445a12e1d..447aa29ffe 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -60,6 +60,16 @@ class TimestampTest < ActiveRecord::TestCase Developer.record_timestamps = true end + def test_saving_when_instance_record_timestamps_is_false_doesnt_update_its_timestamp + @developer.record_timestamps = false + assert Developer.record_timestamps + + @developer.name = "John Smith" + @developer.save! + + assert_equal @previously_updated_at, @developer.updated_at + end + def test_touching_an_attribute_updates_timestamp previously_created_at = @developer.created_at @developer.touch(:created_at) diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 85f222bca2..f8b3e01a49 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -6,7 +6,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase fixtures :topics class TopicWithCallbacks < ActiveRecord::Base - set_table_name :topics + self.table_name = :topics after_commit{|record| record.send(:do_after_commit, nil)} after_commit(:on => :create){|record| record.send(:do_after_commit, :create)} @@ -252,7 +252,7 @@ class TransactionObserverCallbacksTest < ActiveRecord::TestCase fixtures :topics class TopicWithObserverAttached < ActiveRecord::Base - set_table_name :topics + self.table_name = :topics def history @history ||= [] end diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 110a18772f..203dd054f1 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -563,6 +563,7 @@ if current_adapter?(:PostgreSQLAdapter) topic.approved = !topic.approved? topic.save! end + Topic.connection.close end end @@ -598,6 +599,7 @@ if current_adapter?(:PostgreSQLAdapter) dev = Developer.find(1) assert_equal original_salary, dev.salary end + Developer.connection.close end end @@ -610,6 +612,7 @@ if current_adapter?(:PostgreSQLAdapter) assert_equal original_salary, Developer.find(1).salary end end + Developer.connection.close end threads.each { |t| t.join } diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index f85fb4e5da..5a69054445 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -4,16 +4,16 @@ class TestRecord < ActiveRecord::Base end class TestUnconnectedAdapter < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_fixtures = false def setup - @underlying = ActiveRecord::Base.connection - @specification = ActiveRecord::Base.remove_connection + @underlying = ActiveRecord::Model.connection + @specification = ActiveRecord::Model.remove_connection end def teardown @underlying = nil - ActiveRecord::Base.establish_connection(@specification) + ActiveRecord::Model.establish_connection(@specification) load_schema if in_memory_db? end diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb index 56e345990f..f155b9bc40 100644 --- a/activerecord/test/cases/validations/association_validation_test.rb +++ b/activerecord/test/cases/validations/association_validation_test.rb @@ -61,6 +61,16 @@ class AssociationValidationTest < ActiveRecord::TestCase assert r.valid? end + def test_validates_associated_marked_for_destruction + Topic.validates_associated(:replies) + Reply.validates_presence_of(:content) + t = Topic.new + t.replies << Reply.new + assert t.invalid? + t.replies.first.mark_for_destruction + assert t.valid? + end + def test_validates_associated_with_custom_message_using_quotes Reply.validates_associated :topic, :message=> "This string contains 'single' and \"double\" quotes" Topic.validates_presence_of :content @@ -81,14 +91,12 @@ class AssociationValidationTest < ActiveRecord::TestCase end def test_validates_size_of_association_utf8 - with_kcode('UTF8') do - assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 } - o = Owner.new('name' => 'あいうえおかきくけこ') - assert !o.save - assert o.errors[:pets].any? - o.pets.build('name' => 'あいうえおかきくけこ') - assert o.valid? - end + assert_nothing_raised { Owner.validates_size_of :pets, :minimum => 1 } + o = Owner.new('name' => 'あいうえおかきくけこ') + assert !o.save + assert o.errors[:pets].any? + o.pets.build('name' => 'あいうえおかきくけこ') + assert o.valid? end def test_validates_presence_of_belongs_to_association__parent_is_new_record diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 0f1b3667cc..382ad0a06a 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -149,16 +149,14 @@ class UniquenessValidationTest < ActiveRecord::TestCase assert t2.valid?, "should validate with nil" assert t2.save, "should save with nil" - with_kcode('UTF8') do - t_utf8 = Topic.new("title" => "Я тоже уникальный!") - assert t_utf8.save, "Should save t_utf8 as unique" - - # If database hasn't UTF-8 character set, this test fails - if Topic.find(t_utf8, :select => 'LOWER(title) AS title').title == "я тоже уникальный!" - t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!") - assert !t2_utf8.valid?, "Shouldn't be valid" - assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique" - end + t_utf8 = Topic.new("title" => "Я тоже уникальный!") + assert t_utf8.save, "Should save t_utf8 as unique" + + # If database hasn't UTF-8 character set, this test fails + if Topic.find(t_utf8, :select => 'LOWER(title) AS title').title == "я тоже уникальный!" + t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!") + assert !t2_utf8.valid?, "Shouldn't be valid" + assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique" end end @@ -256,13 +254,11 @@ class UniquenessValidationTest < ActiveRecord::TestCase end def test_validate_uniqueness_with_limit_and_utf8 - with_kcode('UTF8') do - # Event.title is limited to 5 characters - e1 = Event.create(:title => "一二三四五") - assert e1.valid?, "Could not create an event with a unique, 5 character title" - e2 = Event.create(:title => "一二三四五六七八") - assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" - end + # Event.title is limited to 5 characters + e1 = Event.create(:title => "一二三四五") + assert e1.valid?, "Could not create an event with a unique, 5 character title" + e2 = Event.create(:title => "一二三四五六七八") + assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" end def test_validate_straight_inheritance_uniqueness diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index c3e494866b..e575a98170 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -8,7 +8,7 @@ require 'models/parrot' require 'models/company' class ProtectedPerson < ActiveRecord::Base - set_table_name 'people' + self.table_name = 'people' attr_accessor :addon attr_protected :first_name end diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 0b54c309d1..2b4ec81199 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -5,10 +5,16 @@ class YamlSerializationTest < ActiveRecord::TestCase fixtures :topics def test_to_yaml_with_time_with_zone_should_not_raise_exception + tz = Time.zone Time.zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"] ActiveRecord::Base.time_zone_aware_attributes = true + topic = Topic.new(:written_on => DateTime.now) assert_nothing_raised { topic.to_yaml } + + ensure + Time.zone = tz + ActiveRecord::Base.time_zone_aware_attributes = false end def test_roundtrip @@ -18,6 +24,11 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal topic, t end + def test_roundtrip_serialized_column + topic = Topic.new(:content => {:omg=>:lol}) + assert_equal({:omg=>:lol}, YAML.load(YAML.dump(topic)).content) + end + def test_encode_with_coder topic = Topic.first coder = {} diff --git a/activerecord/test/fixtures/admin/randomly_named_a9.yml b/activerecord/test/fixtures/admin/randomly_named_a9.yml new file mode 100644 index 0000000000..bc51c83112 --- /dev/null +++ b/activerecord/test/fixtures/admin/randomly_named_a9.yml @@ -0,0 +1,7 @@ +first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/admin/randomly_named_b0.yml b/activerecord/test/fixtures/admin/randomly_named_b0.yml new file mode 100644 index 0000000000..bc51c83112 --- /dev/null +++ b/activerecord/test/fixtures/admin/randomly_named_b0.yml @@ -0,0 +1,7 @@ +first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/other_topics.yml b/activerecord/test/fixtures/other_topics.yml new file mode 100644 index 0000000000..93f48aedc4 --- /dev/null +++ b/activerecord/test/fixtures/other_topics.yml @@ -0,0 +1,42 @@ +first: + id: 1 + title: The First Topic + author_name: David + author_email_address: david@loudthinking.com + written_on: 2003-07-16t15:28:11.2233+01:00 + last_read: 2004-04-15 + bonus_time: 2005-01-30t15:28:00.00+01:00 + content: Have a nice day + approved: false + replies_count: 1 + +second: + id: 2 + title: The Second Topic of the day + author_name: Mary + written_on: 2004-07-15t15:28:00.0099+01:00 + content: Have a nice day + approved: true + replies_count: 0 + parent_id: 1 + type: Reply + +third: + id: 3 + title: The Third Topic of the day + author_name: Carl + written_on: 2005-07-15t15:28:00.0099+01:00 + content: I'm a troll + approved: true + replies_count: 1 + +fourth: + id: 4 + title: The Fourth Topic of the day + author_name: Carl + written_on: 2006-07-15t15:28:00.0099+01:00 + content: Why not? + approved: true + type: Reply + parent_id: 3 + diff --git a/activerecord/test/fixtures/randomly_named_a9.yml b/activerecord/test/fixtures/randomly_named_a9.yml new file mode 100644 index 0000000000..bc51c83112 --- /dev/null +++ b/activerecord/test/fixtures/randomly_named_a9.yml @@ -0,0 +1,7 @@ +first_instance:
+ some_attribute: AAA
+ another_attribute: 000
+
+second_instance:
+ some_attribute: BBB
+ another_attribute: 999
diff --git a/activerecord/test/fixtures/teapots.yml b/activerecord/test/fixtures/teapots.yml new file mode 100644 index 0000000000..ff515beb45 --- /dev/null +++ b/activerecord/test/fixtures/teapots.yml @@ -0,0 +1,3 @@ +bob: + id: 1 + name: Bob diff --git a/activerecord/test/migrations/rename/1_we_need_things.rb b/activerecord/test/migrations/rename/1_we_need_things.rb new file mode 100644 index 0000000000..cdbe0b1679 --- /dev/null +++ b/activerecord/test/migrations/rename/1_we_need_things.rb @@ -0,0 +1,11 @@ +class WeNeedThings < ActiveRecord::Migration + def self.up + create_table("things") do |t| + t.column :content, :text + end + end + + def self.down + drop_table "things" + end +end
\ No newline at end of file diff --git a/activerecord/test/migrations/rename/2_rename_things.rb b/activerecord/test/migrations/rename/2_rename_things.rb new file mode 100644 index 0000000000..d441b71fc9 --- /dev/null +++ b/activerecord/test/migrations/rename/2_rename_things.rb @@ -0,0 +1,9 @@ +class RenameThings < ActiveRecord::Migration + def self.up + rename_table "things", "awesome_things" + end + + def self.down + rename_table "awesome_things", "things" + end +end
\ No newline at end of file diff --git a/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb new file mode 100644 index 0000000000..e438cf5999 --- /dev/null +++ b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb @@ -0,0 +1,9 @@ +class PeopleHaveLastNames < ActiveRecord::Migration + def self.up + add_column "people", "hobbies", :string + end + + def self.down + remove_column "people", "hobbies" + end +end diff --git a/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb new file mode 100644 index 0000000000..06cb911117 --- /dev/null +++ b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb @@ -0,0 +1,9 @@ +class ValidPeopleHaveLastNames < ActiveRecord::Migration + def self.up + add_column "people", "last_name", :string + end + + def self.down + remove_column "people", "last_name" + end +end diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb new file mode 100644 index 0000000000..d5e71ce8ef --- /dev/null +++ b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb @@ -0,0 +1,12 @@ +class WeNeedReminders < ActiveRecord::Migration + def self.up + create_table("reminders") do |t| + t.column :content, :text + t.column :remind_at, :datetime + end + end + + def self.down + drop_table "reminders" + end +end
\ No newline at end of file diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb new file mode 100644 index 0000000000..21c9ca5328 --- /dev/null +++ b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb @@ -0,0 +1,12 @@ +class InnocentJointable < ActiveRecord::Migration + def self.up + create_table("people_reminders", :id => false) do |t| + t.column :reminder_id, :integer + t.column :person_id, :integer + end + end + + def self.down + drop_table "people_reminders" + end +end
\ No newline at end of file diff --git a/activerecord/test/models/admin/randomly_named_c1.rb b/activerecord/test/models/admin/randomly_named_c1.rb new file mode 100644 index 0000000000..2f81d5b831 --- /dev/null +++ b/activerecord/test/models/admin/randomly_named_c1.rb @@ -0,0 +1,3 @@ +class Admin::ClassNameThatDoesNotFollowCONVENTIONS < ActiveRecord::Base
+ self.table_name = :randomly_named_table
+end
diff --git a/activerecord/test/models/admin/user.rb b/activerecord/test/models/admin/user.rb index 74bb21551e..c12c88e195 100644 --- a/activerecord/test/models/admin/user.rb +++ b/activerecord/test/models/admin/user.rb @@ -1,3 +1,4 @@ class Admin::User < ActiveRecord::Base belongs_to :account -end
\ No newline at end of file + store :settings, :accessors => [ :color, :homepage ] +end diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 23db5650d4..881e387c8f 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -3,7 +3,7 @@ class Author < ActiveRecord::Base has_many :very_special_comments, :through => :posts has_many :posts_with_comments, :include => :comments, :class_name => "Post" has_many :popular_grouped_posts, :include => :comments, :class_name => "Post", :group => "type", :having => "SUM(comments_count) > 1", :select => "type" - has_many :posts_with_comments_sorted_by_comment_id, :include => :comments, :class_name => "Post", :order => 'comments.id' + has_many :posts_with_comments_sorted_by_comment_id, :eager_load => :comments, :class_name => "Post", :order => 'comments.id' has_many :posts_sorted_by_id_limited, :class_name => "Post", :order => 'posts.id', :limit => 1 has_many :posts_with_categories, :include => :categories, :class_name => "Post" has_many :posts_with_comments_and_categories, :include => [ :comments, :categories ], :order => "posts.id", :class_name => "Post" @@ -54,7 +54,7 @@ class Author < ActiveRecord::Base has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'" has_many :hello_post_comments, :through => :hello_posts, :source => :comments - has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :include => :comments + has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :eager_load => :comments has_many :hello_posts_with_hash_conditions, :class_name => "Post", :conditions => {:body => 'hello'} @@ -128,7 +128,6 @@ class Author < ActiveRecord::Base belongs_to :author_address, :dependent => :destroy belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress" - has_many :post_categories, :through => :posts, :source => :categories has_many :category_post_comments, :through => :categories, :source => :post_comments has_many :misc_posts, :class_name => 'Post', diff --git a/activerecord/test/models/bird.rb b/activerecord/test/models/bird.rb index e61d48e6a5..dff099c1fb 100644 --- a/activerecord/test/models/bird.rb +++ b/activerecord/test/models/bird.rb @@ -1,9 +1,12 @@ class Bird < ActiveRecord::Base + belongs_to :pirate validates_presence_of :name + accepts_nested_attributes_for :pirate + attr_accessor :cancel_save_from_callback before_save :cancel_save_callback_method, :if => :cancel_save_from_callback def cancel_save_callback_method false end -end
\ No newline at end of file +end diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb index 02b85fd38a..3cd63f0660 100644 --- a/activerecord/test/models/category.rb +++ b/activerecord/test/models/category.rb @@ -2,7 +2,7 @@ class Category < ActiveRecord::Base has_and_belongs_to_many :posts has_and_belongs_to_many :special_posts, :class_name => "Post" has_and_belongs_to_many :other_posts, :class_name => "Post" - has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, :class_name => "Post", :include => :authors, :order => "authors.id" + has_and_belongs_to_many :posts_with_authors_sorted_by_author_id, :class_name => "Post", :eager_load => :authors, :order => "authors.id" has_and_belongs_to_many(:select_testing_posts, :class_name => 'Post', diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index c1f7a4171a..fe9c465c81 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -4,7 +4,7 @@ end class Company < AbstractCompany attr_protected :rating - set_sequence_name :companies_nonstd_seq + self.sequence_name = :companies_nonstd_seq validates_presence_of :name @@ -42,6 +42,7 @@ class Firm < Company :before_remove => :log_before_remove, :after_remove => :log_after_remove has_many :unsorted_clients, :class_name => "Client" + has_many :unsorted_clients_with_symbol, :class_name => :Client has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC" has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id" has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false diff --git a/activerecord/test/models/country.rb b/activerecord/test/models/country.rb index 15e3a1de0b..7db9a4e731 100644 --- a/activerecord/test/models/country.rb +++ b/activerecord/test/models/country.rb @@ -1,6 +1,6 @@ class Country < ActiveRecord::Base - set_primary_key :country_id + self.primary_key = :country_id has_and_belongs_to_many :treaties diff --git a/activerecord/test/models/dashboard.rb b/activerecord/test/models/dashboard.rb index a8a25834b1..1b3b54545f 100644 --- a/activerecord/test/models/dashboard.rb +++ b/activerecord/test/models/dashboard.rb @@ -1,3 +1,3 @@ class Dashboard < ActiveRecord::Base - set_primary_key :dashboard_id -end
\ No newline at end of file + self.primary_key = :dashboard_id +end diff --git a/activerecord/test/models/joke.rb b/activerecord/test/models/joke.rb index d7f01e59e6..edda4655dc 100644 --- a/activerecord/test/models/joke.rb +++ b/activerecord/test/models/joke.rb @@ -1,7 +1,7 @@ class Joke < ActiveRecord::Base - set_table_name 'funny_jokes' + self.table_name = 'funny_jokes' end class GoodJoke < ActiveRecord::Base - set_table_name 'funny_jokes' + self.table_name = 'funny_jokes' end diff --git a/activerecord/test/models/keyboard.rb b/activerecord/test/models/keyboard.rb index 32a4a7fad0..39347e274e 100644 --- a/activerecord/test/models/keyboard.rb +++ b/activerecord/test/models/keyboard.rb @@ -1,3 +1,3 @@ class Keyboard < ActiveRecord::Base - set_primary_key 'key_number' + self.primary_key = 'key_number' end diff --git a/activerecord/test/models/legacy_thing.rb b/activerecord/test/models/legacy_thing.rb index eaeb642d12..eead181a0e 100644 --- a/activerecord/test/models/legacy_thing.rb +++ b/activerecord/test/models/legacy_thing.rb @@ -1,3 +1,3 @@ class LegacyThing < ActiveRecord::Base - set_locking_column :version + self.locking_column = :version end diff --git a/activerecord/test/models/liquid.rb b/activerecord/test/models/liquid.rb index b96c054f6c..3fcd5e4b69 100644 --- a/activerecord/test/models/liquid.rb +++ b/activerecord/test/models/liquid.rb @@ -1,5 +1,5 @@ class Liquid < ActiveRecord::Base - set_table_name :liquid + self.table_name = :liquid has_many :molecules, :uniq => true end diff --git a/activerecord/test/models/minivan.rb b/activerecord/test/models/minivan.rb index 830cdb5796..4fe79720ad 100644 --- a/activerecord/test/models/minivan.rb +++ b/activerecord/test/models/minivan.rb @@ -1,5 +1,5 @@ class Minivan < ActiveRecord::Base - set_primary_key :minivan_id + self.primary_key = :minivan_id belongs_to :speedometer has_one :dashboard, :through => :speedometer diff --git a/activerecord/test/models/mixed_case_monkey.rb b/activerecord/test/models/mixed_case_monkey.rb index 853f2682b3..763baefd91 100644 --- a/activerecord/test/models/mixed_case_monkey.rb +++ b/activerecord/test/models/mixed_case_monkey.rb @@ -1,3 +1,3 @@ class MixedCaseMonkey < ActiveRecord::Base - set_primary_key 'monkeyID' + self.primary_key = 'monkeyID' end diff --git a/activerecord/test/models/owner.rb b/activerecord/test/models/owner.rb index 5760b991ec..fea55f4535 100644 --- a/activerecord/test/models/owner.rb +++ b/activerecord/test/models/owner.rb @@ -1,5 +1,5 @@ class Owner < ActiveRecord::Base - set_primary_key :owner_id + self.primary_key = :owner_id has_many :pets has_many :toys, :through => :pets end diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb index 737ef9131b..c4ee2bd19d 100644 --- a/activerecord/test/models/parrot.rb +++ b/activerecord/test/models/parrot.rb @@ -1,5 +1,6 @@ class Parrot < ActiveRecord::Base - set_inheritance_column :parrot_sti_class + self.inheritance_column = :parrot_sti_class + has_and_belongs_to_many :pirates has_and_belongs_to_many :treasures has_many :loots, :as => :looter diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index 967a3625aa..5792b4705b 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -3,13 +3,13 @@ class Person < ActiveRecord::Base has_one :reader has_many :posts, :through => :readers - has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, :conditions => 'comments.id is null' + has_many :posts_with_no_comments, :through => :readers, :source => :post, :eager_load => :comments, :conditions => 'comments.id is null' has_many :references has_many :bad_references has_many :fixed_bad_references, :conditions => { :favourite => true }, :class_name => 'BadReference' has_one :favourite_reference, :class_name => 'Reference', :conditions => ['favourite=?', true] - has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :include => :comments, :order => 'comments.id' + has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :eager_load => :comments, :order => 'comments.id' has_many :jobs, :through => :references has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy @@ -54,7 +54,7 @@ class LoosePerson < ActiveRecord::Base self.table_name = 'people' self.abstract_class = true - attr_protected :comments + attr_protected :comments, :best_friend_id, :best_friend_of_id attr_protected :as => :admin has_one :best_friend, :class_name => 'LoosePerson', :foreign_key => :best_friend_id @@ -81,4 +81,4 @@ class TightPerson < ActiveRecord::Base accepts_nested_attributes_for :best_friend, :best_friend_of, :best_friends end -class TightDescendant < TightPerson; end
\ No newline at end of file +class TightDescendant < TightPerson; end diff --git a/activerecord/test/models/pet.rb b/activerecord/test/models/pet.rb index 113826756a..3cd5bceed5 100644 --- a/activerecord/test/models/pet.rb +++ b/activerecord/test/models/pet.rb @@ -2,7 +2,7 @@ class Pet < ActiveRecord::Base attr_accessor :current_user - set_primary_key :pet_id + self.primary_key = :pet_id belongs_to :owner, :touch => true has_many :toys diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 198a963cbc..1cab78d8c7 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -24,6 +24,10 @@ class Post < ActiveRecord::Base belongs_to :author_with_posts, :class_name => "Author", :foreign_key => :author_id, :include => :posts belongs_to :author_with_address, :class_name => "Author", :foreign_key => :author_id, :include => :author_address + def first_comment + super.body + end + has_one :first_comment, :class_name => 'Comment', :order => 'id ASC' has_one :last_comment, :class_name => 'Comment', :order => 'id desc' scope :with_special_comments, :joins => :comments, :conditions => {:comments => {:type => 'SpecialComment'} } @@ -40,6 +44,10 @@ class Post < ActiveRecord::Base def newest created.last end + + def the_association + proxy_association + end end has_many :author_favorites, :through => :author @@ -181,4 +189,4 @@ end class SpecialPostWithDefaultScope < ActiveRecord::Base self.table_name = 'posts' default_scope where(:id => [1, 5,6]) -end
\ No newline at end of file +end diff --git a/activerecord/test/models/randomly_named_c1.rb b/activerecord/test/models/randomly_named_c1.rb new file mode 100644 index 0000000000..18a86c4989 --- /dev/null +++ b/activerecord/test/models/randomly_named_c1.rb @@ -0,0 +1,3 @@ +class ClassNameThatDoesNotFollowCONVENTIONS < ActiveRecord::Base
+ self.table_name = :randomly_named_table
+end
diff --git a/activerecord/test/models/speedometer.rb b/activerecord/test/models/speedometer.rb index 94743eff8e..0a7d38d8ec 100644 --- a/activerecord/test/models/speedometer.rb +++ b/activerecord/test/models/speedometer.rb @@ -1,4 +1,4 @@ class Speedometer < ActiveRecord::Base - set_primary_key :speedometer_id + self.primary_key = :speedometer_id belongs_to :dashboard -end
\ No newline at end of file +end diff --git a/activerecord/test/models/string_key_object.rb b/activerecord/test/models/string_key_object.rb index f8d4c6e0e4..f084ec1bdc 100644 --- a/activerecord/test/models/string_key_object.rb +++ b/activerecord/test/models/string_key_object.rb @@ -1,3 +1,3 @@ class StringKeyObject < ActiveRecord::Base - set_primary_key :id + self.primary_key = :id end diff --git a/activerecord/test/models/subscriber.rb b/activerecord/test/models/subscriber.rb index 5b78014e6f..76e85a0cd3 100644 --- a/activerecord/test/models/subscriber.rb +++ b/activerecord/test/models/subscriber.rb @@ -1,5 +1,5 @@ class Subscriber < ActiveRecord::Base - set_primary_key 'nick' + self.primary_key = 'nick' has_many :subscriptions has_many :books, :through => :subscriptions end diff --git a/activerecord/test/models/teapot.rb b/activerecord/test/models/teapot.rb new file mode 100644 index 0000000000..b035b18c1b --- /dev/null +++ b/activerecord/test/models/teapot.rb @@ -0,0 +1,35 @@ +class Teapot + # I'm a little teapot, + # Short and stout, + # Here is my handle + # Here is my spout + # When I get all steamed up, + # Hear me shout, + # Tip me over and pour me out! + # + # HELL YEAH TEAPOT SONG + + include ActiveRecord::Model +end + +class OtherTeapot < Teapot +end + +class OMFGIMATEAPOT + def aaahhh + "mmm" + end +end + +class CoolTeapot < OMFGIMATEAPOT + include ActiveRecord::Model + self.table_name = "teapots" +end + +class Ceiling + include ActiveRecord::Model + + class Teapot + include ActiveRecord::Model + end +end diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index fe424e61b2..1a1a18166a 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -8,6 +8,8 @@ class Topic < ActiveRecord::Base scope :approved, :conditions => {:approved => true} scope :rejected, :conditions => {:approved => false} + scope :scope_with_lambda, lambda { scoped } + scope :by_lifo, :conditions => {:author_name => 'lifo'} scope :approved_as_hash_condition, :conditions => {:topics => {:approved => true}} @@ -106,6 +108,10 @@ class Topic < ActiveRecord::Base def after_create_for_transaction; end end +class ImportantTopic < Topic + serialize :important, Hash +end + module Web class Topic < ActiveRecord::Base has_many :replies, :dependent => :destroy, :foreign_key => "parent_id", :class_name => 'Web::Reply' diff --git a/activerecord/test/models/toy.rb b/activerecord/test/models/toy.rb index 6c45e99671..0377e50011 100644 --- a/activerecord/test/models/toy.rb +++ b/activerecord/test/models/toy.rb @@ -1,5 +1,5 @@ class Toy < ActiveRecord::Base - set_primary_key :toy_id + self.primary_key = :toy_id belongs_to :pet scope :with_pet, joins(:pet) diff --git a/activerecord/test/models/treaty.rb b/activerecord/test/models/treaty.rb index b46537f0d2..41fd1350f3 100644 --- a/activerecord/test/models/treaty.rb +++ b/activerecord/test/models/treaty.rb @@ -1,6 +1,6 @@ class Treaty < ActiveRecord::Base - set_primary_key :treaty_id + self.primary_key = :treaty_id has_and_belongs_to_many :countries diff --git a/activerecord/test/models/warehouse_thing.rb b/activerecord/test/models/warehouse_thing.rb index 6ace1183cc..f20bd1a245 100644 --- a/activerecord/test/models/warehouse_thing.rb +++ b/activerecord/test/models/warehouse_thing.rb @@ -1,5 +1,5 @@ class WarehouseThing < ActiveRecord::Base - set_table_name "warehouse-things" + self.table_name = "warehouse-things" validates_uniqueness_of :value -end
\ No newline at end of file +end diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb index c78d99f4af..ab2c7ccc10 100644 --- a/activerecord/test/schema/mysql2_specific_schema.rb +++ b/activerecord/test/schema/mysql2_specific_schema.rb @@ -21,4 +21,15 @@ BEGIN END SQL -end + ActiveRecord::Base.connection.execute <<-SQL +DROP TABLE IF EXISTS collation_tests; +SQL + + ActiveRecord::Base.connection.execute <<-SQL +CREATE TABLE collation_tests ( + string_cs_column VARCHAR(1) COLLATE utf8_bin, + string_ci_column VARCHAR(1) COLLATE utf8_general_ci +) CHARACTER SET utf8 COLLATE utf8_general_ci +SQL + +end
\ No newline at end of file diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb index 30e1c5a167..a0adfe3752 100644 --- a/activerecord/test/schema/mysql_specific_schema.rb +++ b/activerecord/test/schema/mysql_specific_schema.rb @@ -32,4 +32,15 @@ BEGIN END SQL + ActiveRecord::Base.connection.execute <<-SQL +DROP TABLE IF EXISTS collation_tests; +SQL + + ActiveRecord::Base.connection.execute <<-SQL +CREATE TABLE collation_tests ( + string_cs_column VARCHAR(1) COLLATE utf8_bin, + string_ci_column VARCHAR(1) COLLATE utf8_general_ci +) CHARACTER SET utf8 COLLATE utf8_general_ci +SQL + end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 62cfe3ae94..11378c12e5 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -37,6 +37,7 @@ ActiveRecord::Schema.define do create_table :admin_users, :force => true do |t| t.string :name + t.text :settings t.references :account end @@ -505,6 +506,11 @@ ActiveRecord::Schema.define do t.string :type end + create_table :randomly_named_table, :force => true do |t| + t.string :some_attribute + t.integer :another_attribute + end + create_table :ratings, :force => true do |t| t.integer :comment_id t.integer :value @@ -596,6 +602,12 @@ ActiveRecord::Schema.define do t.datetime :ending end + create_table :teapots, :force => true do |t| + t.string :name + t.string :type + t.timestamps + end + create_table :topics, :force => true do |t| t.string :title t.string :author_name @@ -607,8 +619,10 @@ ActiveRecord::Schema.define do # Oracle SELECT WHERE clause which causes many unit test failures if current_adapter?(:OracleAdapter) t.string :content, :limit => 4000 + t.string :important, :limit => 4000 else t.text :content + t.text :important end t.boolean :approved, :default => true t.integer :replies_count, :default => 0 diff --git a/activerecord/test/support/connection.rb b/activerecord/test/support/connection.rb index a39794fa39..60fea46fd3 100644 --- a/activerecord/test/support/connection.rb +++ b/activerecord/test/support/connection.rb @@ -1,4 +1,4 @@ -require 'logger' +require 'active_support/logger' require_dependency 'models/course' module ARTest @@ -12,9 +12,9 @@ module ARTest def self.connect puts "Using #{connection_name} with Identity Map #{ActiveRecord::IdentityMap.enabled? ? 'on' : 'off'}" - ActiveRecord::Base.logger = Logger.new("debug.log") - ActiveRecord::Base.configurations = connection_config - ActiveRecord::Base.establish_connection 'arunit' + ActiveRecord::Model.logger = ActiveSupport::Logger.new("debug.log") + ActiveRecord::Model.configurations = connection_config + ActiveRecord::Model.establish_connection 'arunit' Course.establish_connection 'arunit2' end end |