rails 2.2.2 → 3.0.0
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- data/bin/rails +8 -18
- metadata +118 -452
- data/CHANGELOG +0 -2071
- data/MIT-LICENSE +0 -20
- data/README +0 -256
- data/Rakefile +0 -411
- data/bin/about +0 -4
- data/bin/console +0 -3
- data/bin/dbconsole +0 -3
- data/bin/destroy +0 -3
- data/bin/generate +0 -3
- data/bin/performance/benchmarker +0 -3
- data/bin/performance/profiler +0 -3
- data/bin/performance/request +0 -3
- data/bin/plugin +0 -3
- data/bin/process/inspector +0 -3
- data/bin/process/reaper +0 -3
- data/bin/process/spawner +0 -3
- data/bin/runner +0 -3
- data/bin/server +0 -3
- data/builtin/rails_info/rails/info.rb +0 -125
- data/builtin/rails_info/rails/info_controller.rb +0 -9
- data/builtin/rails_info/rails/info_helper.rb +0 -2
- data/builtin/rails_info/rails_info_controller.rb +0 -2
- data/config.ru +0 -17
- data/configs/apache.conf +0 -40
- data/configs/databases/frontbase.yml +0 -28
- data/configs/databases/ibm_db.yml +0 -62
- data/configs/databases/mysql.yml +0 -57
- data/configs/databases/oracle.yml +0 -39
- data/configs/databases/postgresql.yml +0 -51
- data/configs/databases/sqlite2.yml +0 -19
- data/configs/databases/sqlite3.yml +0 -22
- data/configs/empty.log +0 -0
- data/configs/initializers/inflections.rb +0 -10
- data/configs/initializers/mime_types.rb +0 -5
- data/configs/initializers/new_rails_defaults.rb +0 -17
- data/configs/lighttpd.conf +0 -54
- data/configs/locales/en.yml +0 -5
- data/configs/routes.rb +0 -43
- data/dispatches/dispatch.fcgi +0 -24
- data/dispatches/dispatch.rb +0 -10
- data/dispatches/gateway.cgi +0 -97
- data/doc/README_FOR_APP +0 -5
- data/doc/guides/html/2_2_release_notes.html +0 -1185
- data/doc/guides/html/actioncontroller_basics.html +0 -1270
- data/doc/guides/html/activerecord_validations_callbacks.html +0 -749
- data/doc/guides/html/association_basics.html +0 -2585
- data/doc/guides/html/authors.html +0 -240
- data/doc/guides/html/benchmarking_and_profiling.html +0 -1018
- data/doc/guides/html/caching_with_rails.html +0 -583
- data/doc/guides/html/command_line.html +0 -434
- data/doc/guides/html/configuring.html +0 -438
- data/doc/guides/html/creating_plugins.html +0 -1594
- data/doc/guides/html/debugging_rails_applications.html +0 -1175
- data/doc/guides/html/finders.html +0 -1090
- data/doc/guides/html/form_helpers.html +0 -638
- data/doc/guides/html/getting_started_with_rails.html +0 -2066
- data/doc/guides/html/index.html +0 -349
- data/doc/guides/html/layouts_and_rendering.html +0 -1406
- data/doc/guides/html/migrations.html +0 -921
- data/doc/guides/html/routing_outside_in.html +0 -2213
- data/doc/guides/html/security.html +0 -1346
- data/doc/guides/html/testing_rails_applications.html +0 -1859
- data/doc/guides/source/2_2_release_notes.txt +0 -435
- data/doc/guides/source/actioncontroller_basics/changelog.txt +0 -5
- data/doc/guides/source/actioncontroller_basics/cookies.txt +0 -34
- data/doc/guides/source/actioncontroller_basics/csrf.txt +0 -32
- data/doc/guides/source/actioncontroller_basics/filters.txt +0 -119
- data/doc/guides/source/actioncontroller_basics/http_auth.txt +0 -24
- data/doc/guides/source/actioncontroller_basics/index.txt +0 -40
- data/doc/guides/source/actioncontroller_basics/introduction.txt +0 -9
- data/doc/guides/source/actioncontroller_basics/methods.txt +0 -39
- data/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +0 -14
- data/doc/guides/source/actioncontroller_basics/params.txt +0 -93
- data/doc/guides/source/actioncontroller_basics/request_response_objects.txt +0 -43
- data/doc/guides/source/actioncontroller_basics/rescue.txt +0 -67
- data/doc/guides/source/actioncontroller_basics/session.txt +0 -187
- data/doc/guides/source/actioncontroller_basics/streaming.txt +0 -91
- data/doc/guides/source/actioncontroller_basics/verification.txt +0 -40
- data/doc/guides/source/active_record_basics.txt +0 -181
- data/doc/guides/source/activerecord_validations_callbacks.txt +0 -404
- data/doc/guides/source/association_basics.txt +0 -1840
- data/doc/guides/source/authors.txt +0 -39
- data/doc/guides/source/benchmarking_and_profiling/appendix.txt +0 -95
- data/doc/guides/source/benchmarking_and_profiling/digging_deeper.txt +0 -105
- data/doc/guides/source/benchmarking_and_profiling/edge_rails_features.txt +0 -185
- data/doc/guides/source/benchmarking_and_profiling/gameplan.txt +0 -27
- data/doc/guides/source/benchmarking_and_profiling/index.txt +0 -242
- data/doc/guides/source/benchmarking_and_profiling/rubyprof.txt +0 -179
- data/doc/guides/source/benchmarking_and_profiling/statistics.txt +0 -57
- data/doc/guides/source/caching_with_rails.txt +0 -367
- data/doc/guides/source/command_line.txt +0 -147
- data/doc/guides/source/configuring.txt +0 -225
- data/doc/guides/source/creating_plugins/acts_as_yaffle.txt +0 -191
- data/doc/guides/source/creating_plugins/appendix.txt +0 -46
- data/doc/guides/source/creating_plugins/controllers.txt +0 -59
- data/doc/guides/source/creating_plugins/core_ext.txt +0 -123
- data/doc/guides/source/creating_plugins/custom_route.txt +0 -69
- data/doc/guides/source/creating_plugins/gem.txt +0 -1
- data/doc/guides/source/creating_plugins/generator_method.txt +0 -89
- data/doc/guides/source/creating_plugins/helpers.txt +0 -51
- data/doc/guides/source/creating_plugins/index.txt +0 -52
- data/doc/guides/source/creating_plugins/migration_generator.txt +0 -156
- data/doc/guides/source/creating_plugins/models.txt +0 -76
- data/doc/guides/source/creating_plugins/odds_and_ends.txt +0 -69
- data/doc/guides/source/creating_plugins/test_setup.txt +0 -230
- data/doc/guides/source/debugging_rails_applications.txt +0 -733
- data/doc/guides/source/finders.txt +0 -668
- data/doc/guides/source/form_helpers.txt +0 -345
- data/doc/guides/source/getting_started_with_rails.txt +0 -1256
- data/doc/guides/source/images/belongs_to.png +0 -0
- data/doc/guides/source/images/bullet.gif +0 -0
- data/doc/guides/source/images/csrf.png +0 -0
- data/doc/guides/source/images/habtm.png +0 -0
- data/doc/guides/source/images/has_many.png +0 -0
- data/doc/guides/source/images/has_many_through.png +0 -0
- data/doc/guides/source/images/has_one.png +0 -0
- data/doc/guides/source/images/has_one_through.png +0 -0
- data/doc/guides/source/images/header_backdrop.png +0 -0
- data/doc/guides/source/images/icons/README +0 -5
- data/doc/guides/source/images/icons/callouts/1.png +0 -0
- data/doc/guides/source/images/icons/callouts/10.png +0 -0
- data/doc/guides/source/images/icons/callouts/11.png +0 -0
- data/doc/guides/source/images/icons/callouts/12.png +0 -0
- data/doc/guides/source/images/icons/callouts/13.png +0 -0
- data/doc/guides/source/images/icons/callouts/14.png +0 -0
- data/doc/guides/source/images/icons/callouts/15.png +0 -0
- data/doc/guides/source/images/icons/callouts/2.png +0 -0
- data/doc/guides/source/images/icons/callouts/3.png +0 -0
- data/doc/guides/source/images/icons/callouts/4.png +0 -0
- data/doc/guides/source/images/icons/callouts/5.png +0 -0
- data/doc/guides/source/images/icons/callouts/6.png +0 -0
- data/doc/guides/source/images/icons/callouts/7.png +0 -0
- data/doc/guides/source/images/icons/callouts/8.png +0 -0
- data/doc/guides/source/images/icons/callouts/9.png +0 -0
- data/doc/guides/source/images/icons/caution.png +0 -0
- data/doc/guides/source/images/icons/example.png +0 -0
- data/doc/guides/source/images/icons/home.png +0 -0
- data/doc/guides/source/images/icons/important.png +0 -0
- data/doc/guides/source/images/icons/next.png +0 -0
- data/doc/guides/source/images/icons/note.png +0 -0
- data/doc/guides/source/images/icons/prev.png +0 -0
- data/doc/guides/source/images/icons/tip.png +0 -0
- data/doc/guides/source/images/icons/up.png +0 -0
- data/doc/guides/source/images/icons/warning.png +0 -0
- data/doc/guides/source/images/polymorphic.png +0 -0
- data/doc/guides/source/images/rails_logo_remix.gif +0 -0
- data/doc/guides/source/images/ruby_on_rails_by_mike_rundle2.gif +0 -0
- data/doc/guides/source/images/session_fixation.png +0 -0
- data/doc/guides/source/index.txt +0 -118
- data/doc/guides/source/layouts_and_rendering.txt +0 -982
- data/doc/guides/source/migrations/anatomy_of_a_migration.txt +0 -85
- data/doc/guides/source/migrations/changelog.txt +0 -5
- data/doc/guides/source/migrations/creating_a_migration.txt +0 -109
- data/doc/guides/source/migrations/foreign_keys.txt +0 -8
- data/doc/guides/source/migrations/index.txt +0 -22
- data/doc/guides/source/migrations/rakeing_around.txt +0 -111
- data/doc/guides/source/migrations/scheming.txt +0 -47
- data/doc/guides/source/migrations/using_models_in_migrations.txt +0 -46
- data/doc/guides/source/migrations/writing_a_migration.txt +0 -159
- data/doc/guides/source/routing_outside_in.txt +0 -986
- data/doc/guides/source/security.txt +0 -984
- data/doc/guides/source/stylesheets/base.css +0 -358
- data/doc/guides/source/stylesheets/forms.css +0 -35
- data/doc/guides/source/stylesheets/more.css +0 -82
- data/doc/guides/source/templates/guides.html.erb +0 -97
- data/doc/guides/source/templates/inline.css +0 -165
- data/doc/guides/source/testing_rails_applications.txt +0 -995
- data/environments/boot.rb +0 -109
- data/environments/development.rb +0 -17
- data/environments/environment.rb +0 -75
- data/environments/production.rb +0 -24
- data/environments/test.rb +0 -22
- data/fresh_rakefile +0 -10
- data/helpers/application.rb +0 -15
- data/helpers/application_helper.rb +0 -3
- data/helpers/performance_test.rb +0 -9
- data/helpers/test_helper.rb +0 -38
- data/html/404.html +0 -30
- data/html/422.html +0 -30
- data/html/500.html +0 -33
- data/html/favicon.ico +0 -0
- data/html/images/rails.png +0 -0
- data/html/index.html +0 -274
- data/html/javascripts/application.js +0 -2
- data/html/javascripts/controls.js +0 -963
- data/html/javascripts/dragdrop.js +0 -973
- data/html/javascripts/effects.js +0 -1128
- data/html/javascripts/prototype.js +0 -4320
- data/html/robots.txt +0 -5
- data/lib/code_statistics.rb +0 -107
- data/lib/commands.rb +0 -17
- data/lib/commands/about.rb +0 -3
- data/lib/commands/console.rb +0 -45
- data/lib/commands/dbconsole.rb +0 -67
- data/lib/commands/destroy.rb +0 -6
- data/lib/commands/generate.rb +0 -6
- data/lib/commands/ncgi/listener +0 -86
- data/lib/commands/ncgi/tracker +0 -69
- data/lib/commands/performance/benchmarker.rb +0 -24
- data/lib/commands/performance/profiler.rb +0 -50
- data/lib/commands/performance/request.rb +0 -6
- data/lib/commands/plugin.rb +0 -967
- data/lib/commands/process/inspector.rb +0 -68
- data/lib/commands/process/reaper.rb +0 -149
- data/lib/commands/process/spawner.rb +0 -219
- data/lib/commands/process/spinner.rb +0 -57
- data/lib/commands/runner.rb +0 -48
- data/lib/commands/server.rb +0 -49
- data/lib/commands/servers/base.rb +0 -31
- data/lib/commands/servers/lighttpd.rb +0 -94
- data/lib/commands/servers/mongrel.rb +0 -69
- data/lib/commands/servers/new_mongrel.rb +0 -16
- data/lib/commands/servers/thin.rb +0 -25
- data/lib/commands/servers/webrick.rb +0 -66
- data/lib/commands/update.rb +0 -4
- data/lib/console_app.rb +0 -30
- data/lib/console_sandbox.rb +0 -6
- data/lib/console_with_helpers.rb +0 -26
- data/lib/dispatcher.rb +0 -24
- data/lib/fcgi_handler.rb +0 -237
- data/lib/initializer.rb +0 -1038
- data/lib/performance_test_help.rb +0 -5
- data/lib/rails/gem_builder.rb +0 -21
- data/lib/rails/gem_dependency.rb +0 -251
- data/lib/rails/mongrel_server/commands.rb +0 -342
- data/lib/rails/mongrel_server/handler.rb +0 -55
- data/lib/rails/plugin.rb +0 -124
- data/lib/rails/plugin/loader.rb +0 -152
- data/lib/rails/plugin/locator.rb +0 -100
- data/lib/rails/rack.rb +0 -6
- data/lib/rails/rack/logger.rb +0 -28
- data/lib/rails/rack/static.rb +0 -35
- data/lib/rails/vendor_gem_source_index.rb +0 -140
- data/lib/rails/version.rb +0 -9
- data/lib/rails_generator.rb +0 -43
- data/lib/rails_generator/base.rb +0 -263
- data/lib/rails_generator/commands.rb +0 -616
- data/lib/rails_generator/generated_attribute.rb +0 -46
- data/lib/rails_generator/generators/applications/app/USAGE +0 -9
- data/lib/rails_generator/generators/applications/app/app_generator.rb +0 -184
- data/lib/rails_generator/generators/components/controller/USAGE +0 -29
- data/lib/rails_generator/generators/components/controller/controller_generator.rb +0 -37
- data/lib/rails_generator/generators/components/controller/templates/controller.rb +0 -7
- data/lib/rails_generator/generators/components/controller/templates/functional_test.rb +0 -8
- data/lib/rails_generator/generators/components/controller/templates/helper.rb +0 -2
- data/lib/rails_generator/generators/components/controller/templates/view.html.erb +0 -2
- data/lib/rails_generator/generators/components/integration_test/USAGE +0 -8
- data/lib/rails_generator/generators/components/integration_test/integration_test_generator.rb +0 -16
- data/lib/rails_generator/generators/components/integration_test/templates/integration_test.rb +0 -10
- data/lib/rails_generator/generators/components/mailer/USAGE +0 -16
- data/lib/rails_generator/generators/components/mailer/mailer_generator.rb +0 -30
- data/lib/rails_generator/generators/components/mailer/templates/fixture.erb +0 -3
- data/lib/rails_generator/generators/components/mailer/templates/fixture.rhtml +0 -0
- data/lib/rails_generator/generators/components/mailer/templates/mailer.rb +0 -15
- data/lib/rails_generator/generators/components/mailer/templates/unit_test.rb +0 -20
- data/lib/rails_generator/generators/components/mailer/templates/view.erb +0 -3
- data/lib/rails_generator/generators/components/mailer/templates/view.rhtml +0 -0
- data/lib/rails_generator/generators/components/migration/USAGE +0 -29
- data/lib/rails_generator/generators/components/migration/migration_generator.rb +0 -20
- data/lib/rails_generator/generators/components/migration/templates/migration.rb +0 -11
- data/lib/rails_generator/generators/components/model/USAGE +0 -27
- data/lib/rails_generator/generators/components/model/model_generator.rb +0 -45
- data/lib/rails_generator/generators/components/model/templates/fixtures.yml +0 -19
- data/lib/rails_generator/generators/components/model/templates/migration.rb +0 -16
- data/lib/rails_generator/generators/components/model/templates/model.rb +0 -5
- data/lib/rails_generator/generators/components/model/templates/unit_test.rb +0 -8
- data/lib/rails_generator/generators/components/observer/USAGE +0 -13
- data/lib/rails_generator/generators/components/observer/observer_generator.rb +0 -16
- data/lib/rails_generator/generators/components/observer/templates/observer.rb +0 -2
- data/lib/rails_generator/generators/components/observer/templates/unit_test.rb +0 -8
- data/lib/rails_generator/generators/components/performance_test/USAGE +0 -8
- data/lib/rails_generator/generators/components/performance_test/performance_test_generator.rb +0 -16
- data/lib/rails_generator/generators/components/performance_test/templates/performance_test.rb +0 -9
- data/lib/rails_generator/generators/components/plugin/USAGE +0 -25
- data/lib/rails_generator/generators/components/plugin/plugin_generator.rb +0 -39
- data/lib/rails_generator/generators/components/plugin/templates/MIT-LICENSE +0 -20
- data/lib/rails_generator/generators/components/plugin/templates/README +0 -13
- data/lib/rails_generator/generators/components/plugin/templates/Rakefile +0 -23
- data/lib/rails_generator/generators/components/plugin/templates/USAGE +0 -8
- data/lib/rails_generator/generators/components/plugin/templates/generator.rb +0 -8
- data/lib/rails_generator/generators/components/plugin/templates/init.rb +0 -1
- data/lib/rails_generator/generators/components/plugin/templates/install.rb +0 -1
- data/lib/rails_generator/generators/components/plugin/templates/plugin.rb +0 -1
- data/lib/rails_generator/generators/components/plugin/templates/tasks.rake +0 -4
- data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +0 -3
- data/lib/rails_generator/generators/components/plugin/templates/uninstall.rb +0 -1
- data/lib/rails_generator/generators/components/plugin/templates/unit_test.rb +0 -8
- data/lib/rails_generator/generators/components/resource/USAGE +0 -23
- data/lib/rails_generator/generators/components/resource/resource_generator.rb +0 -74
- data/lib/rails_generator/generators/components/resource/templates/controller.rb +0 -2
- data/lib/rails_generator/generators/components/resource/templates/functional_test.rb +0 -8
- data/lib/rails_generator/generators/components/resource/templates/helper.rb +0 -2
- data/lib/rails_generator/generators/components/scaffold/USAGE +0 -29
- data/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +0 -100
- data/lib/rails_generator/generators/components/scaffold/templates/controller.rb +0 -85
- data/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb +0 -45
- data/lib/rails_generator/generators/components/scaffold/templates/helper.rb +0 -2
- data/lib/rails_generator/generators/components/scaffold/templates/layout.html.erb +0 -17
- data/lib/rails_generator/generators/components/scaffold/templates/style.css +0 -54
- data/lib/rails_generator/generators/components/scaffold/templates/view_edit.html.erb +0 -18
- data/lib/rails_generator/generators/components/scaffold/templates/view_index.html.erb +0 -24
- data/lib/rails_generator/generators/components/scaffold/templates/view_new.html.erb +0 -17
- data/lib/rails_generator/generators/components/scaffold/templates/view_show.html.erb +0 -10
- data/lib/rails_generator/generators/components/session_migration/USAGE +0 -10
- data/lib/rails_generator/generators/components/session_migration/session_migration_generator.rb +0 -18
- data/lib/rails_generator/generators/components/session_migration/templates/migration.rb +0 -16
- data/lib/rails_generator/lookup.rb +0 -249
- data/lib/rails_generator/manifest.rb +0 -53
- data/lib/rails_generator/options.rb +0 -150
- data/lib/rails_generator/scripts.rb +0 -89
- data/lib/rails_generator/scripts/destroy.rb +0 -29
- data/lib/rails_generator/scripts/generate.rb +0 -7
- data/lib/rails_generator/scripts/update.rb +0 -12
- data/lib/rails_generator/secret_key_generator.rb +0 -22
- data/lib/rails_generator/simple_logger.rb +0 -46
- data/lib/rails_generator/spec.rb +0 -44
- data/lib/railties_path.rb +0 -1
- data/lib/ruby_version_check.rb +0 -17
- data/lib/rubyprof_ext.rb +0 -35
- data/lib/source_annotation_extractor.rb +0 -102
- data/lib/tasks/annotations.rake +0 -20
- data/lib/tasks/databases.rake +0 -416
- data/lib/tasks/documentation.rake +0 -95
- data/lib/tasks/framework.rake +0 -118
- data/lib/tasks/gems.rake +0 -80
- data/lib/tasks/log.rake +0 -9
- data/lib/tasks/misc.rake +0 -56
- data/lib/tasks/rails.rb +0 -8
- data/lib/tasks/routes.rake +0 -17
- data/lib/tasks/statistics.rake +0 -18
- data/lib/tasks/testing.rake +0 -139
- data/lib/tasks/tmp.rake +0 -37
- data/lib/test_help.rb +0 -27
- data/lib/webrick_server.rb +0 -156
@@ -1,668 +0,0 @@
|
|
1
|
-
Rails Finders
|
2
|
-
=============
|
3
|
-
|
4
|
-
This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to:
|
5
|
-
|
6
|
-
* Find records using a variety of methods and conditions
|
7
|
-
* Specify the order, retrieved attributes, grouping, and other properties of the found records
|
8
|
-
* Use eager loading to cut down on the number of database queries in your application
|
9
|
-
* Use dynamic finders
|
10
|
-
* Create named scopes to add custom finding behavior to your models
|
11
|
-
* Check for the existence of particular records
|
12
|
-
* Perform aggregate calculations on Active Record models
|
13
|
-
|
14
|
-
If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
|
15
|
-
|
16
|
-
== The Sample Models
|
17
|
-
|
18
|
-
This guide demonstrates finding using the following models:
|
19
|
-
|
20
|
-
[source,ruby]
|
21
|
-
-------------------------------------------------------
|
22
|
-
class Client < ActiveRecord::Base
|
23
|
-
has_one :address
|
24
|
-
has_one :mailing_address
|
25
|
-
has_many :orders
|
26
|
-
has_and_belongs_to_many :roles
|
27
|
-
end
|
28
|
-
|
29
|
-
class Address < ActiveRecord::Base
|
30
|
-
belongs_to :client
|
31
|
-
end
|
32
|
-
|
33
|
-
class MailingAddress < Address
|
34
|
-
end
|
35
|
-
|
36
|
-
class Order < ActiveRecord::Base
|
37
|
-
belongs_to :client, :counter_cache => true
|
38
|
-
end
|
39
|
-
|
40
|
-
class Role < ActiveRecord::Base
|
41
|
-
has_and_belongs_to_many :clients
|
42
|
-
end
|
43
|
-
-------------------------------------------------------
|
44
|
-
|
45
|
-
== Database Agnostic
|
46
|
-
|
47
|
-
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.
|
48
|
-
|
49
|
-
== IDs, First, Last and All
|
50
|
-
|
51
|
-
+ActiveRecord::Base+ has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is +find+. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type +Client.find(1)+ which would execute this query on your database:
|
52
|
-
|
53
|
-
[source, sql]
|
54
|
-
-------------------------------------------------------
|
55
|
-
SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1)
|
56
|
-
-------------------------------------------------------
|
57
|
-
|
58
|
-
NOTE: Because this is a standard table created from a migration in Rail, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
|
59
|
-
|
60
|
-
If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +Client.find(1,2)+ and then this will be executed as:
|
61
|
-
|
62
|
-
[source, sql]
|
63
|
-
-------------------------------------------------------
|
64
|
-
SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
|
65
|
-
-------------------------------------------------------
|
66
|
-
|
67
|
-
-------------------------------------------------------
|
68
|
-
>> Client.find(1,2)
|
69
|
-
=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
|
70
|
-
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
|
71
|
-
#<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
|
72
|
-
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
|
73
|
-
-------------------------------------------------------
|
74
|
-
|
75
|
-
Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object.
|
76
|
-
|
77
|
-
NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
|
78
|
-
|
79
|
-
If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
|
80
|
-
|
81
|
-
-------------------------------------------------------
|
82
|
-
>> Client.first
|
83
|
-
=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
|
84
|
-
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
|
85
|
-
-------------------------------------------------------
|
86
|
-
|
87
|
-
If you were running script/server you might see the following output:
|
88
|
-
|
89
|
-
[source,sql]
|
90
|
-
-------------------------------------------------------
|
91
|
-
SELECT * FROM clients LIMIT 1
|
92
|
-
-------------------------------------------------------
|
93
|
-
|
94
|
-
Indicating the query that Rails has performed on your database.
|
95
|
-
|
96
|
-
To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
|
97
|
-
|
98
|
-
-------------------------------------------------------
|
99
|
-
>> Client.find(:last)
|
100
|
-
=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
|
101
|
-
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
|
102
|
-
-------------------------------------------------------
|
103
|
-
|
104
|
-
[source,sql]
|
105
|
-
-------------------------------------------------------
|
106
|
-
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
|
107
|
-
-------------------------------------------------------
|
108
|
-
|
109
|
-
To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table:
|
110
|
-
|
111
|
-
-------------------------------------------------------
|
112
|
-
>> Client.all
|
113
|
-
=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
|
114
|
-
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
|
115
|
-
#<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
|
116
|
-
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
|
117
|
-
-------------------------------------------------------
|
118
|
-
|
119
|
-
As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively.
|
120
|
-
|
121
|
-
Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to find will do also.
|
122
|
-
|
123
|
-
== Conditions
|
124
|
-
|
125
|
-
The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.
|
126
|
-
|
127
|
-
=== Pure String Conditions ===
|
128
|
-
|
129
|
-
If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
|
130
|
-
|
131
|
-
WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
|
132
|
-
|
133
|
-
=== Array Conditions ===
|
134
|
-
|
135
|
-
Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
|
136
|
-
|
137
|
-
The reason for doing code like:
|
138
|
-
|
139
|
-
[source, ruby]
|
140
|
-
-------------------------------------------------------
|
141
|
-
+Client.first(:conditions => ["orders_count = ?", params[:orders]])+
|
142
|
-
-------------------------------------------------------
|
143
|
-
|
144
|
-
instead of:
|
145
|
-
|
146
|
-
-------------------------------------------------------
|
147
|
-
+Client.first(:conditions => "orders_count = #{params[:orders]}")+
|
148
|
-
-------------------------------------------------------
|
149
|
-
|
150
|
-
is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
|
151
|
-
|
152
|
-
TIP: For more information on the dangers of SQL injection, see the link:../security.html#_sql_injection[Ruby on Rails Security Guide].
|
153
|
-
|
154
|
-
If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the IN sql statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
|
155
|
-
|
156
|
-
[source, ruby]
|
157
|
-
-------------------------------------------------------
|
158
|
-
Client.all(:conditions => ["created_at IN (?)",
|
159
|
-
(params[:start_date].to_date)..(params[:end_date].to_date)])
|
160
|
-
-------------------------------------------------------
|
161
|
-
|
162
|
-
This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.
|
163
|
-
|
164
|
-
[source, sql]
|
165
|
-
-------------------------------------------------------
|
166
|
-
SELECT * FROM +users+ WHERE (created_at IN
|
167
|
-
('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
|
168
|
-
'2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
|
169
|
-
'2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
|
170
|
-
'2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
|
171
|
-
‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
|
172
|
-
'2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
|
173
|
-
'2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
|
174
|
-
-------------------------------------------------------
|
175
|
-
|
176
|
-
Things can get *really* messy if you pass in time objects as it will attempt to compare your field to *every second* in that range:
|
177
|
-
|
178
|
-
[source, ruby]
|
179
|
-
-------------------------------------------------------
|
180
|
-
Client.all(:conditions => ["created_at IN (?)",
|
181
|
-
(params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
|
182
|
-
-------------------------------------------------------
|
183
|
-
|
184
|
-
[source, sql]
|
185
|
-
-------------------------------------------------------
|
186
|
-
SELECT * FROM +users+ WHERE (created_at IN
|
187
|
-
('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
|
188
|
-
'2007-12-01 23:59:59', '2007-12-02 00:00:00'))
|
189
|
-
-------------------------------------------------------
|
190
|
-
|
191
|
-
This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
|
192
|
-
|
193
|
-
-------------------------------------------------------
|
194
|
-
Got a packet bigger than 'max_allowed_packet' bytes: _query_
|
195
|
-
-------------------------------------------------------
|
196
|
-
|
197
|
-
Where _query_ is the actual query used to get that error.
|
198
|
-
|
199
|
-
In this example it would be better to use greater-than and less-than operators in SQL, like so:
|
200
|
-
|
201
|
-
[source, ruby]
|
202
|
-
-------------------------------------------------------
|
203
|
-
Client.all(:conditions =>
|
204
|
-
["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
|
205
|
-
-------------------------------------------------------
|
206
|
-
|
207
|
-
You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:
|
208
|
-
|
209
|
-
[source, ruby]
|
210
|
-
-------------------------------------------------------
|
211
|
-
Client.all(:conditions =>
|
212
|
-
["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
|
213
|
-
-------------------------------------------------------
|
214
|
-
|
215
|
-
Just like in Ruby.
|
216
|
-
|
217
|
-
=== Hash Conditions ===
|
218
|
-
|
219
|
-
Similar to the array style of params you can also specify keys in your conditions:
|
220
|
-
|
221
|
-
[source, ruby]
|
222
|
-
-------------------------------------------------------
|
223
|
-
Client.all(:conditions =>
|
224
|
-
["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
|
225
|
-
-------------------------------------------------------
|
226
|
-
|
227
|
-
This makes for clearer readability if you have a large number of variable conditions.
|
228
|
-
|
229
|
-
== Ordering
|
230
|
-
|
231
|
-
If you're getting a set of records and want to force an order, you can use +Client.all(:order => "created_at")+ which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using +Client.all(:order => "created_at desc")+
|
232
|
-
|
233
|
-
== Selecting Certain Fields
|
234
|
-
|
235
|
-
To select certain fields, you can use the select option like this: +Client.first(:select => "viewable_by, locked")+. This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute +SELECT viewable_by, locked FROM clients LIMIT 0,1+ on your database.
|
236
|
-
|
237
|
-
== Limit & Offset
|
238
|
-
|
239
|
-
If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:
|
240
|
-
|
241
|
-
[source, ruby]
|
242
|
-
-------------------------------------------------------
|
243
|
-
Client.all(:limit => 5)
|
244
|
-
-------------------------------------------------------
|
245
|
-
|
246
|
-
This code will return a maximum of 5 clients and because it specifies no offset it will return the first 5 clients in the table. The SQL it executes will look like this:
|
247
|
-
|
248
|
-
[source,sql]
|
249
|
-
-------------------------------------------------------
|
250
|
-
SELECT * FROM clients LIMIT 5
|
251
|
-
-------------------------------------------------------
|
252
|
-
|
253
|
-
[source, ruby]
|
254
|
-
-------------------------------------------------------
|
255
|
-
Client.all(:limit => 5, :offset => 5)
|
256
|
-
-------------------------------------------------------
|
257
|
-
|
258
|
-
This code will return a maximum of 5 clients and because it specifies an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:
|
259
|
-
|
260
|
-
[source,sql]
|
261
|
-
-------------------------------------------------------
|
262
|
-
SELECT * FROM clients LIMIT 5, 5
|
263
|
-
-------------------------------------------------------
|
264
|
-
|
265
|
-
== Group
|
266
|
-
|
267
|
-
The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:
|
268
|
-
|
269
|
-
[source, ruby]
|
270
|
-
-------------------------------------------------------
|
271
|
-
Order.all(:group => "date(created_at)", :order => "created_at")
|
272
|
-
-------------------------------------------------------
|
273
|
-
|
274
|
-
And this will give you a single +Order+ object for each date where there are orders in the database.
|
275
|
-
|
276
|
-
The SQL that would be executed would be something like this:
|
277
|
-
|
278
|
-
[source, sql]
|
279
|
-
-------------------------------------------------------
|
280
|
-
SELECT * FROM +orders+ GROUP BY date(created_at)
|
281
|
-
-------------------------------------------------------
|
282
|
-
|
283
|
-
== Read Only
|
284
|
-
|
285
|
-
Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this:
|
286
|
-
|
287
|
-
[source, ruby]
|
288
|
-
-------------------------------------------------------
|
289
|
-
Client.first(:readonly => true)
|
290
|
-
-------------------------------------------------------
|
291
|
-
|
292
|
-
If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception:
|
293
|
-
|
294
|
-
[source, ruby]
|
295
|
-
-------------------------------------------------------
|
296
|
-
client = Client.first(:readonly => true)
|
297
|
-
client.locked = false
|
298
|
-
client.save
|
299
|
-
-------------------------------------------------------
|
300
|
-
|
301
|
-
== Lock
|
302
|
-
|
303
|
-
If you're wanting to stop race conditions for a specific record (for example, you're incrementing a single field for a record, potentially from multiple simultaneous connections) you can use the lock option to ensure that the record is updated correctly. For safety, you should use this inside a transaction.
|
304
|
-
|
305
|
-
[source, ruby]
|
306
|
-
-------------------------------------------------------
|
307
|
-
Topic.transaction do
|
308
|
-
t = Topic.find(params[:id], :lock => true)
|
309
|
-
t.increment!(:views)
|
310
|
-
end
|
311
|
-
-------------------------------------------------------
|
312
|
-
|
313
|
-
== Making It All Work Together
|
314
|
-
|
315
|
-
You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.
|
316
|
-
|
317
|
-
== Eager Loading
|
318
|
-
|
319
|
-
Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:
|
320
|
-
|
321
|
-
[source, sql]
|
322
|
-
-------------------------------------------------------
|
323
|
-
Client Load (0.000383) SELECT * FROM clients
|
324
|
-
Address Load (0.119770) SELECT addresses.* FROM addresses
|
325
|
-
WHERE (addresses.client_id IN (13,14))
|
326
|
-
MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM
|
327
|
-
mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
|
328
|
-
-------------------------------------------------------
|
329
|
-
|
330
|
-
The numbers +13+ and +14+ in the above SQL are the ids of the clients gathered from the +Client.all+ query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called +address+ or +mailing_address+ on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.
|
331
|
-
|
332
|
-
If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+ and you wanted to find the address and mailing address for that client you would do +Client.all(:joins => [:address, :mailing_address])+. This is more efficient because it does all the SQL in one query, as shown by this example:
|
333
|
-
|
334
|
-
[source, sql]
|
335
|
-
-------------------------------------------------------
|
336
|
-
+Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses
|
337
|
-
ON addresses.client_id = client.id INNER JOIN mailing_addresses ON
|
338
|
-
mailing_addresses.client_id = client.id
|
339
|
-
-------------------------------------------------------
|
340
|
-
|
341
|
-
This query is more efficent, but there's a gotcha: if you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins. Alternatively, you can use a SQL join clause to specify exactly the join you need (Rails always assumes an inner join):
|
342
|
-
|
343
|
-
[source, ruby]
|
344
|
-
-------------------------------------------------------
|
345
|
-
Client.all(:joins => “LEFT OUTER JOIN addresses ON
|
346
|
-
client.id = addresses.client_id LEFT OUTER JOIN mailing_addresses ON
|
347
|
-
client.id = mailing_addresses.client_id”)
|
348
|
-
-------------------------------------------------------
|
349
|
-
|
350
|
-
When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:
|
351
|
-
|
352
|
-
[source, ruby]
|
353
|
-
-------------------------------------------------------
|
354
|
-
Client.first(:include => "orders", :conditions =>
|
355
|
-
["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
|
356
|
-
-------------------------------------------------------
|
357
|
-
|
358
|
-
== Dynamic finders
|
359
|
-
|
360
|
-
For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type +find_by_name(params[:name])+ than it is to type +first(:conditions => ["name = ?", params[:name]])+.
|
361
|
-
|
362
|
-
There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name('Ryan')+:
|
363
|
-
|
364
|
-
[source,sql]
|
365
|
-
-------------------------------------------------------
|
366
|
-
SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1
|
367
|
-
BEGIN
|
368
|
-
INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+)
|
369
|
-
VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
|
370
|
-
COMMIT
|
371
|
-
-------------------------------------------------------
|
372
|
-
|
373
|
-
+find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will call +new+ with the parameters you passed in. For example:
|
374
|
-
|
375
|
-
[source, ruby]
|
376
|
-
-------------------------------------------------------
|
377
|
-
client = Client.find_or_initialize_by_name('Ryan')
|
378
|
-
-------------------------------------------------------
|
379
|
-
|
380
|
-
will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it.
|
381
|
-
|
382
|
-
== Finding By SQL
|
383
|
-
|
384
|
-
If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
|
385
|
-
|
386
|
-
[source, ruby]
|
387
|
-
-------------------------------------------------------
|
388
|
-
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
|
389
|
-
-------------------------------------------------------
|
390
|
-
|
391
|
-
+find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
|
392
|
-
|
393
|
-
== +select_all+ ==
|
394
|
-
|
395
|
-
+find_by_sql+ has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
|
396
|
-
|
397
|
-
[source, ruby]
|
398
|
-
-------------------------------------------------------
|
399
|
-
Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
|
400
|
-
-------------------------------------------------------
|
401
|
-
|
402
|
-
== Working with Associations
|
403
|
-
|
404
|
-
When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers.
|
405
|
-
|
406
|
-
== Named Scopes
|
407
|
-
|
408
|
-
Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.
|
409
|
-
|
410
|
-
=== Simple Named Scopes
|
411
|
-
|
412
|
-
Suppose want to find all clients who are male. You could use this code:
|
413
|
-
|
414
|
-
[source, ruby]
|
415
|
-
-------------------------------------------------------
|
416
|
-
class Client < ActiveRecord::Base
|
417
|
-
named_scope :males, :conditions => { :gender => "male" }
|
418
|
-
end
|
419
|
-
-------------------------------------------------------
|
420
|
-
|
421
|
-
Then you could call +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end.
|
422
|
-
|
423
|
-
If you wanted to find all the clients who are active, you could use this:
|
424
|
-
|
425
|
-
[source,ruby]
|
426
|
-
-------------------------------------------------------
|
427
|
-
class Client < ActiveRecord::Base
|
428
|
-
named_scope :active, :conditions => { :active => true }
|
429
|
-
end
|
430
|
-
-------------------------------------------------------
|
431
|
-
|
432
|
-
You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+.
|
433
|
-
|
434
|
-
=== Combining Named Scopes
|
435
|
-
|
436
|
-
If you wanted to find all the clients who are active and male you can stack the named scopes like this:
|
437
|
-
|
438
|
-
[source, ruby]
|
439
|
-
-------------------------------------------------------
|
440
|
-
Client.males.active.all
|
441
|
-
-------------------------------------------------------
|
442
|
-
|
443
|
-
If you would then like to do a +all+ on that scope, you can. Just like an association, named scopes allow you to call +all+ on them:
|
444
|
-
|
445
|
-
[source, ruby]
|
446
|
-
-------------------------------------------------------
|
447
|
-
Client.males.active.all(:conditions => ["age > ?", params[:age]])
|
448
|
-
-------------------------------------------------------
|
449
|
-
|
450
|
-
=== Runtime Evaluation of Named Scope Conditions
|
451
|
-
|
452
|
-
Consider the following code:
|
453
|
-
|
454
|
-
[source, ruby]
|
455
|
-
-------------------------------------------------------
|
456
|
-
class Client < ActiveRecord::Base
|
457
|
-
named_scope :recent, :conditions => { :created_at > 2.weeks.ago }
|
458
|
-
end
|
459
|
-
-------------------------------------------------------
|
460
|
-
|
461
|
-
This looks like a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, +2.weeks.ago+ is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:
|
462
|
-
|
463
|
-
[source, ruby]
|
464
|
-
-------------------------------------------------------
|
465
|
-
class Client < ActiveRecord::Base
|
466
|
-
named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } }
|
467
|
-
end
|
468
|
-
-------------------------------------------------------
|
469
|
-
|
470
|
-
And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.
|
471
|
-
|
472
|
-
=== Named Scopes with Multiple Models
|
473
|
-
|
474
|
-
In a named scope you can use +:include+ and +:joins+ options just like in find.
|
475
|
-
|
476
|
-
[source, ruby]
|
477
|
-
-------------------------------------------------------
|
478
|
-
class Client < ActiveRecord::Base
|
479
|
-
named_scope :active_within_2_weeks, :joins => :order,
|
480
|
-
lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
|
481
|
-
end
|
482
|
-
-------------------------------------------------------
|
483
|
-
|
484
|
-
This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks.
|
485
|
-
|
486
|
-
=== Arguments to Named Scopes
|
487
|
-
|
488
|
-
If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:
|
489
|
-
|
490
|
-
[source, ruby]
|
491
|
-
-------------------------------------------------------
|
492
|
-
class Client < ActiveRecord::Base
|
493
|
-
named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } }
|
494
|
-
end
|
495
|
-
-------------------------------------------------------
|
496
|
-
|
497
|
-
This will work if you call +Client.recent(2.weeks.ago).all+ but not if you call +Client.recent+. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.
|
498
|
-
|
499
|
-
[source, ruby]
|
500
|
-
-------------------------------------------------------
|
501
|
-
class Client < ActiveRecord::Base
|
502
|
-
named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } }
|
503
|
-
end
|
504
|
-
-------------------------------------------------------
|
505
|
-
|
506
|
-
This will work with +Client.recent(2.weeks.ago).all+ and +Client.recent.all+, with the latter always returning records with a created_at date between right now and 2 weeks ago.
|
507
|
-
|
508
|
-
Remember that named scopes are stackable, so you will be able to do +Client.recent(2.weeks.ago).unlocked.all+ to find all clients created between right now and 2 weeks ago and have their locked field set to false.
|
509
|
-
|
510
|
-
=== Anonymous Scopes
|
511
|
-
|
512
|
-
All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example:
|
513
|
-
|
514
|
-
[source, ruby]
|
515
|
-
-------------------------------------------------------
|
516
|
-
class Client < ActiveRecord::Base
|
517
|
-
def self.recent
|
518
|
-
scoped :conditions => ["created_at > ?", 2.weeks.ago]
|
519
|
-
end
|
520
|
-
end
|
521
|
-
-------------------------------------------------------
|
522
|
-
|
523
|
-
Anonymous scopes are most useful to create scopes "on the fly":
|
524
|
-
|
525
|
-
[source, ruby]
|
526
|
-
-------------------------------------------------------
|
527
|
-
Client.scoped(:conditions => { :gender => "male" })
|
528
|
-
-------------------------------------------------------
|
529
|
-
|
530
|
-
Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.
|
531
|
-
|
532
|
-
== Existence of Objects
|
533
|
-
|
534
|
-
If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.
|
535
|
-
|
536
|
-
[source, ruby]
|
537
|
-
-------------------------------------------------------
|
538
|
-
Client.exists?(1)
|
539
|
-
-------------------------------------------------------
|
540
|
-
|
541
|
-
The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.
|
542
|
-
|
543
|
-
[source, ruby]
|
544
|
-
-------------------------------------------------------
|
545
|
-
Client.exists?(1,2,3)
|
546
|
-
# or
|
547
|
-
Client.exists?([1,2,3])
|
548
|
-
-------------------------------------------------------
|
549
|
-
|
550
|
-
The +exists?+ method also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.
|
551
|
-
|
552
|
-
Further more, +exists+ takes a +conditions+ option much like find:
|
553
|
-
|
554
|
-
[source, ruby]
|
555
|
-
-------------------------------------------------------
|
556
|
-
Client.exists?(:conditions => "first_name = 'Ryan'")
|
557
|
-
-------------------------------------------------------
|
558
|
-
|
559
|
-
== Calculations
|
560
|
-
|
561
|
-
This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
|
562
|
-
|
563
|
-
+count+ takes conditions much in the same way +exists?+ does:
|
564
|
-
|
565
|
-
[source, ruby]
|
566
|
-
-------------------------------------------------------
|
567
|
-
Client.count(:conditions => "first_name = 'Ryan'")
|
568
|
-
-------------------------------------------------------
|
569
|
-
|
570
|
-
Which will execute:
|
571
|
-
|
572
|
-
[source, sql]
|
573
|
-
-------------------------------------------------------
|
574
|
-
SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1)
|
575
|
-
-------------------------------------------------------
|
576
|
-
|
577
|
-
You can also use +include+ or +joins+ for this to do something a little more complex:
|
578
|
-
|
579
|
-
[source, ruby]
|
580
|
-
-------------------------------------------------------
|
581
|
-
Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders")
|
582
|
-
-------------------------------------------------------
|
583
|
-
|
584
|
-
Which will execute:
|
585
|
-
|
586
|
-
[source, sql]
|
587
|
-
-------------------------------------------------------
|
588
|
-
SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+
|
589
|
-
LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE
|
590
|
-
(clients.first_name = 'name' AND orders.status = 'received')
|
591
|
-
-------------------------------------------------------
|
592
|
-
|
593
|
-
This code specifies +clients.first_name+ just in case one of the join tables has a field also called +first_name+ and it uses +orders.status+ because that's the name of our join table.
|
594
|
-
|
595
|
-
|
596
|
-
=== Count
|
597
|
-
|
598
|
-
If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+.
|
599
|
-
|
600
|
-
For options, please see the parent section, Calculations.
|
601
|
-
|
602
|
-
=== Average
|
603
|
-
|
604
|
-
If you want to see the average of a certain number in one of your tables you can call the +average+ method on the class that relates to the table. This method call will look something like this:
|
605
|
-
|
606
|
-
[source, ruby]
|
607
|
-
-------------------------------------------------------
|
608
|
-
Client.average("orders_count")
|
609
|
-
-------------------------------------------------------
|
610
|
-
|
611
|
-
This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
|
612
|
-
|
613
|
-
For options, please see the parent section, <<_calculations, Calculations>>
|
614
|
-
|
615
|
-
=== Minimum
|
616
|
-
|
617
|
-
If you want to find the minimum value of a field in your table you can call the +minimum+ method on the class that relates to the table. This method call will look something like this:
|
618
|
-
|
619
|
-
[source, ruby]
|
620
|
-
-------------------------------------------------------
|
621
|
-
Client.minimum("age")
|
622
|
-
-------------------------------------------------------
|
623
|
-
|
624
|
-
For options, please see the parent section, <<_calculations, Calculations>>
|
625
|
-
|
626
|
-
=== Maximum
|
627
|
-
|
628
|
-
If you want to find the maximum value of a field in your table you can call the +maximum+ method on the class that relates to the table. This method call will look something like this:
|
629
|
-
|
630
|
-
[source, ruby]
|
631
|
-
-------------------------------------------------------
|
632
|
-
Client.maximum("age")
|
633
|
-
-------------------------------------------------------
|
634
|
-
|
635
|
-
For options, please see the parent section, <<_calculations, Calculations>>
|
636
|
-
|
637
|
-
=== Sum
|
638
|
-
|
639
|
-
If you want to find the sum of a field for all records in your table you can call the +sum+ method on the class that relates to the table. This method call will look something like this:
|
640
|
-
|
641
|
-
[source, ruby]
|
642
|
-
-------------------------------------------------------
|
643
|
-
Client.sum("orders_count")
|
644
|
-
-------------------------------------------------------
|
645
|
-
|
646
|
-
For options, please see the parent section, <<_calculations, Calculations>>
|
647
|
-
|
648
|
-
== Credits
|
649
|
-
|
650
|
-
Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.
|
651
|
-
|
652
|
-
Thanks to Mike Gunderloy for his tips on creating this guide.
|
653
|
-
|
654
|
-
== Changelog
|
655
|
-
|
656
|
-
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
|
657
|
-
|
658
|
-
* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
|
659
|
-
* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
|
660
|
-
* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
|
661
|
-
* October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
|
662
|
-
* October 22, 2008: Calculations complete, first complete draft by Ryan Bigg
|
663
|
-
* October 21, 2008: Extended named scope section by Ryan Bigg
|
664
|
-
* October 9, 2008: Lock, count, cleanup by Ryan Bigg
|
665
|
-
* October 6, 2008: Eager loading by Ryan Bigg
|
666
|
-
* October 5, 2008: Covered conditions by Ryan Bigg
|
667
|
-
* October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg
|
668
|
-
* September 28, 2008: Covered first/last/all by Ryan Bigg
|