diff options
Diffstat (limited to 'railties/doc/guides/activerecord')
-rw-r--r-- | railties/doc/guides/activerecord/association_basics.txt | 34 | ||||
-rw-r--r-- | railties/doc/guides/activerecord/finders.txt | 137 |
2 files changed, 150 insertions, 21 deletions
diff --git a/railties/doc/guides/activerecord/association_basics.txt b/railties/doc/guides/activerecord/association_basics.txt index f9ec7a5f55..df89cfb531 100644 --- a/railties/doc/guides/activerecord/association_basics.txt +++ b/railties/doc/guides/activerecord/association_basics.txt @@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re [source, ruby] ------------------------------------------------------- class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => :user, :foreign_key => "manager_id" - belongs_to :manager, :class_name => :user + has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "User" end ------------------------------------------------------- @@ -636,12 +636,12 @@ The +belongs_to+ association supports these options: // ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is patron, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Order < ActiveRecord::Base - belongs_to :customer, :class_name => :patron + belongs_to :customer, :class_name => "Patron" end ------------------------------------------------------- @@ -711,7 +711,7 @@ By convention, Rails guesses that the column used to hold the foreign key on thi [source, ruby] ------------------------------------------------------- class Order < ActiveRecord::Base - belongs_to :customer, :class_name => :patron, :foreign_key => "patron_id" + belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id" end ------------------------------------------------------- @@ -863,7 +863,7 @@ In many situations, you can use the default behavior of +has_one+ without any cu [source, ruby] ------------------------------------------------------- class Supplier < ActiveRecord::Base - has_one :account, :class_name => :billing, :dependent => :nullify + has_one :account, :class_name => "Billing", :dependent => :nullify end ------------------------------------------------------- @@ -895,12 +895,12 @@ Setting the +:as+ option indicates that this is a polymorphic association. Polym ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is billing, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Supplier < ActiveRecord::Base - has_one :account, :class_name => :billing + has_one :account, :class_name => "Billing" end ------------------------------------------------------- @@ -1205,12 +1205,12 @@ Setting the +:as+ option indicates that this is a polymorphic association, as di ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is transactions, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :orders, :class_name => :transaction + has_many :orders, :class_name => "Transaction" end ------------------------------------------------------- @@ -1221,7 +1221,7 @@ The +:conditions+ option lets you specify the conditions that the associated obj [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :confirmed_orders, :class_name => :orders, :conditions => "confirmed = 1" + has_many :confirmed_orders, :class_name => "Order", :conditions => "confirmed = 1" end ------------------------------------------------------- @@ -1230,7 +1230,7 @@ You can also set conditions via a hash: [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :confirmed_orders, :class_name => :orders, :conditions => { :confirmed => true } + has_many :confirmed_orders, :class_name => "Order", :conditions => { :confirmed => true } end ------------------------------------------------------- @@ -1321,7 +1321,7 @@ The +:limit+ option lets you restrict the total number of objects that will be f [source, ruby] ------------------------------------------------------- class Customer < ActiveRecord::Base - has_many :recent_orders, :class_name => :orders, :order => "order_date DESC", :limit => 100 + has_many :recent_orders, :class_name => "Order", :order => "order_date DESC", :limit => 100 end ------------------------------------------------------- @@ -1591,19 +1591,19 @@ TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when s [source, ruby] ------------------------------------------------------- class User < ActiveRecord::Base - has_and_belongs_to_many :friends, :class_name => :users, + has_and_belongs_to_many :friends, :class_name => "User", :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" end ------------------------------------------------------- ===== +:class_name+ -If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is gadgets, you'd set things up this way: +If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way: [source, ruby] ------------------------------------------------------- class Parts < ActiveRecord::Base - has_and_belongs_to_many :assemblies, :class_name => :gadgets + has_and_belongs_to_many :assemblies, :class_name => "Gadget" end ------------------------------------------------------- @@ -1654,7 +1654,7 @@ By convention, Rails guesses that the column in the join table used to hold the [source, ruby] ------------------------------------------------------- class User < ActiveRecord::Base - has_and_belongs_to_many :friends, :class_name => :users, + has_and_belongs_to_many :friends, :class_name => "User", :foreign_key => "this_user_id", :association_foreign_key => "other_user_id" end ------------------------------------------------------- diff --git a/railties/doc/guides/activerecord/finders.txt b/railties/doc/guides/activerecord/finders.txt index 2547ae3f26..d1169ffdd4 100644 --- a/railties/doc/guides/activerecord/finders.txt +++ b/railties/doc/guides/activerecord/finders.txt @@ -103,6 +103,56 @@ Be aware that `Client.first`/`Client.find(:first)` and `Client.last`/`Client.fin If you'd like to add conditions to your find, you could just specify them in there, just like `Client.find(:first, :conditions => "orders_count = '2'")`. 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.find(:first, :conditions => ["orders_count = ?", params[:orders]])`. ActiveRecord 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.find(: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. +The reason for doing code like: + +[source, ruby] +`Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])` + +instead of: + +`Client.find(:first, :conditions => "orders_count = #{params[:orders]}")` + +is because of parameter safety. Putting the variable directly into the conditions string will parse the variable *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. + +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 we had two dates coming in from a controller we could do something like this to look for a range: + +[source, ruby] +Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date)]) + +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. + +[source, sql] +SELECT * FROM `users` WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05','2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11','2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17','2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',... +2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20','2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26','2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31')) + + +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: + +[source, ruby] +Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)]) + +[source, sql] +SELECT * FROM `users` WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00')) + +This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error: + +[source, txt] +Got a packet bigger than 'max_allowed_packet' bytes: <query> + +Where <query> is the actual query used to get that error. + +In this example it would be better to use greater-than and less-than operators in SQL, like so: + +[source, ruby] +Client.find(:all, :condtions => ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]]) + +You can also use the greater-than-or-equal-to and less-than-or-equal-to like this: + +[source, ruby] +Client.find(:all, :condtions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]]) + +Just like in Ruby. + == Ordering If you're getting a set of records and want to force an order, you can use `Client.find(: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.find(:all, :order => "created_at desc")` @@ -133,6 +183,8 @@ SELECT * FROM clients LIMIT 5, 5 == Group +TODO + == Read Only 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 `ActiveRecord::ReadOnlyRecord` error. To set this option, specify it like this: @@ -149,18 +201,26 @@ client.save == Lock +If you're wanting to stop race conditions for a specific record, say for example you're incrementing a single field for a record you can use the lock option to ensure that the record is updated correctly. It's recommended this be used inside a transaction. + +[source, Ruby] +Topic.transaction do + t = Topic.find(params[:id], :lock => true) + t.increment!(:views) +end + == Making It All Work Together -You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. For example you could do this: `Client.find(:all, :order => "created_at DESC", :select => "viewable_by, created_at", :conditions => ["viewable_by = ?", params[:level]], :limit => 10), which should execute a query like `SELECT viewable_by, created_at FROM clients WHERE ORDER BY created_at DESC LIMIT 0,10` if you really wanted it. +You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter. == Eager Loading Eager loading is loading associated records along with any number of records in as few queries as possible. Lets say for example if we wanted to load all the addresses associated with all the clients all in the same query we would use `Client.find(:all, :include => :address)`. If we wanted to include both the address and mailing address for the client we would use `Client.find(:all), :include => [:address, :mailing_address]). Inclue 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: [source, sql] -Client Load (0.000383) SELECT \* FROM clients -Address Load (0.119770) SELECT addresses.\* FROM addresses WHERE (addresses.client_id IN (13,14)) -MailingAddress Load (0.001985) SELECT mailing_addresses.\* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14)) +Client Load (0.000383) SELECT * FROM clients +Address Load (0.119770) SELECT addresses.* FROM addresses WHERE (addresses.client_id IN (13,14)) +MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14)) The numbers `13` and `14` in the above SQL are the ids of the clients gathered from the `Client.find(: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. @@ -168,8 +228,17 @@ An alternative (and more efficient) way to do eager loading is to use the joins [source, sql] `Client Load (0.000455) SELECT clients.* FROM clients INNER JOIN addresses ON addresses.client_id = client.id INNER JOIN mailing_addresses ON mailing_addresses.client_id = client.id + 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. +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: + +[source, Ruby] + +Client.find(:first, :include => "orders", :conditions => ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now]) + +[source] + == Dynamic finders With every field (also known as an attribute) you define in your table, ActiveRecord provides finder methods for these. 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 ActiveRecord. 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 `find(:first, :conditions => ["name = ?", params[:name]])`. @@ -189,6 +258,15 @@ client = Client.find_or_initialize_by_name('Ryan') 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. +== Finding By SQL + +If you'd like to use your own SQL to find records a table you can use `find_by_sql`. `find_by_sql` 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: + +[source, ruby] +Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc") + +`find_by_sql` provides you with a simple way of making custom calls to the database and converting those to objects. + == Working with Associations 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 exisiting 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. @@ -237,6 +315,45 @@ end This will work with `Client.recent(2.weeks.ago)` and `Client.recent` with the latter always returning records with a created_at date between right now and 2 weeks ago. Remember that named scopes are stackable, so you will be able to do `Client.recent(2.weeks.ago).unlocked` to find all clients created between right now and 2 weeks ago and have their locked field set to false. + +== Existance of Objects + +If you simply want to check for the existance 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. + +[source, ruby] +Client.exists?(1) + +The above code will check for the existance of a clients table record with the id of 1 and return true if it exists. + +[source, ruby] +Client.exists?(1,2,3) +# or +Client.exists?([1,2,3]) + +`exists?` 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. + +Further more, `exists` takes a `conditions` option much like find: + +[source, ruby] +Client.exists?(:conditions => "first_name = 'Ryan'") + +== Calculations + +=== Count + +If you want to see how many records are in your models 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)`. + +`count` takes conditions much in the same way `exists?` does: + +[source, ruby] +Client.count(:conditions => "first_name = 'Ryan'") + +[source, sql] +SELECT count(*) AS count_all FROM `clients` WHERE (first_name = 1) + +== With Scope + +TODO == Credits @@ -258,3 +375,15 @@ Thanks to Mike Gunderloy for his tips on creating this guide. 1. Did section on limit and offset, as well as section on readonly. 2. Altered formatting so it doesn't look bad. + +=== Sunday, 05 October 2008 +1. Extended conditions section to include IN and using operators inside the conditions. +2. Extended conditions section to include paragraph and example of parameter safety. +3. Added TODO sections. + +=== Monday, 06 October 2008 +1. Added section in Eager Loading about using conditions on tables that are not the model's own. + +=== Thursday, 09 October 2008 +1. Wrote section about lock option and tidied up "Making it all work together" section. +2. Added section on using count. |