This repository is private.
All pages are served over SSL and all pushing and pulling is done over SSH.
No one may fork, clone, or view it unless they are added as a member.
Every repository with this icon (
) is private.
Every repository with this icon (
This repository is public.
Anyone may fork, clone, or view it.
Every repository with this icon (
) is public.
Every repository with this icon (
| db045dbb » | dhh | 2004-11-23 | 1 | require 'yaml' | |
| aabf9093 » | jeremy | 2005-11-02 | 2 | require 'set' | |
| db045dbb » | dhh | 2004-11-23 | 3 | ||
| 4 | module ActiveRecord #:nodoc: | ||||
| 98dc5827 » | lifo | 2008-05-25 | 5 | # Generic Active Record exception class. | |
| 73673256 » | jeremy | 2007-12-09 | 6 | class ActiveRecordError < StandardError | |
| db045dbb » | dhh | 2004-11-23 | 7 | end | |
| 73673256 » | jeremy | 2007-12-09 | 8 | ||
| 9 | # Raised when the single-table inheritance mechanism failes to locate the subclass | ||||
| 10 | # (for example due to improper usage of column that +inheritance_column+ points to). | ||||
| 605bc775 » | dhh | 2004-12-14 | 11 | class SubclassNotFound < ActiveRecordError #:nodoc: | |
| 12 | end | ||||
| 73673256 » | jeremy | 2007-12-09 | 13 | ||
| 64092de2 » | fxn | 2008-05-02 | 14 | # Raised when an object assigned to an association has an incorrect type. | |
| 73673256 » | jeremy | 2007-12-09 | 15 | # | |
| 64092de2 » | fxn | 2008-05-02 | 16 | # class Ticket < ActiveRecord::Base | |
| 17 | # has_many :patches | ||||
| 18 | # end | ||||
| 73673256 » | jeremy | 2007-12-09 | 19 | # | |
| 64092de2 » | fxn | 2008-05-02 | 20 | # class Patch < ActiveRecord::Base | |
| 21 | # belongs_to :ticket | ||||
| 22 | # end | ||||
| 73673256 » | jeremy | 2007-12-09 | 23 | # | |
| 64092de2 » | fxn | 2008-05-02 | 24 | # # Comments are not patches, this assignment raises AssociationTypeMismatch. | |
| 25 | # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.") | ||||
| 73673256 » | jeremy | 2007-12-09 | 26 | class AssociationTypeMismatch < ActiveRecordError | |
| db045dbb » | dhh | 2004-11-23 | 27 | end | |
| 73673256 » | jeremy | 2007-12-09 | 28 | ||
| 29 | # Raised when unserialized object's type mismatches one specified for serializable field. | ||||
| 30 | class SerializationTypeMismatch < ActiveRecordError | ||||
| db045dbb » | dhh | 2004-11-23 | 31 | end | |
| 73673256 » | jeremy | 2007-12-09 | 32 | ||
| 98dc5827 » | lifo | 2008-05-25 | 33 | # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field). | |
| 73673256 » | jeremy | 2007-12-09 | 34 | class AdapterNotSpecified < ActiveRecordError | |
| db045dbb » | dhh | 2004-11-23 | 35 | end | |
| 73673256 » | jeremy | 2007-12-09 | 36 | ||
| 98dc5827 » | lifo | 2008-05-25 | 37 | # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically. | |
| 73673256 » | jeremy | 2007-12-09 | 38 | class AdapterNotFound < ActiveRecordError | |
| db045dbb » | dhh | 2004-11-23 | 39 | end | |
| 73673256 » | jeremy | 2007-12-09 | 40 | ||
| 98dc5827 » | lifo | 2008-05-25 | 41 | # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object). | |
| 73673256 » | jeremy | 2007-12-09 | 42 | class ConnectionNotEstablished < ActiveRecordError | |
| db045dbb » | dhh | 2004-11-23 | 43 | end | |
| 73673256 » | jeremy | 2007-12-09 | 44 | ||
| 98dc5827 » | lifo | 2008-05-25 | 45 | # Raised when Active Record cannot find record by given id or set of ids. | |
| 73673256 » | jeremy | 2007-12-09 | 46 | class RecordNotFound < ActiveRecordError | |
| db045dbb » | dhh | 2004-11-23 | 47 | end | |
| 73673256 » | jeremy | 2007-12-09 | 48 | ||
| 49 | # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be | ||||
| 50 | # saved because record is invalid. | ||||
| 51 | class RecordNotSaved < ActiveRecordError | ||||
| 4c7555ae » | dhh | 2006-02-28 | 52 | end | |
| 73673256 » | jeremy | 2007-12-09 | 53 | ||
| 54 | # Raised when SQL statement cannot be executed by the database (for example, it's often the case for MySQL when Ruby driver used is too old). | ||||
| 55 | class StatementInvalid < ActiveRecordError | ||||
| db045dbb » | dhh | 2004-11-23 | 56 | end | |
| 73673256 » | jeremy | 2007-12-09 | 57 | ||
| 64092de2 » | fxn | 2008-05-02 | 58 | # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method) | |
| 73673256 » | jeremy | 2007-12-09 | 59 | # does not match number of expected variables. | |
| 60 | # | ||||
| 64092de2 » | fxn | 2008-05-02 | 61 | # For example, in | |
| 73673256 » | jeremy | 2007-12-09 | 62 | # | |
| 64092de2 » | fxn | 2008-05-02 | 63 | # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362] | |
| 73673256 » | jeremy | 2007-12-09 | 64 | # | |
| 64092de2 » | fxn | 2008-05-02 | 65 | # two placeholders are given but only one variable to fill them. | |
| 73673256 » | jeremy | 2007-12-09 | 66 | class PreparedStatementInvalid < ActiveRecordError | |
| 554597d6 » | dhh | 2004-12-08 | 67 | end | |
| 73673256 » | jeremy | 2007-12-09 | 68 | ||
| 69 | # Raised on attempt to save stale record. Record is stale when it's being saved in another query after | ||||
| 70 | # instantiation, for example, when two users edit the same wiki page and one starts editing and saves | ||||
| 71 | # the page before the other. | ||||
| 72 | # | ||||
| 98dc5827 » | lifo | 2008-05-25 | 73 | # Read more about optimistic locking in ActiveRecord::Locking module RDoc. | |
| 73673256 » | jeremy | 2007-12-09 | 74 | class StaleObjectError < ActiveRecordError | |
| fbf9281f » | dhh | 2004-12-31 | 75 | end | |
| 73673256 » | jeremy | 2007-12-09 | 76 | ||
| 77 | # Raised when association is being configured improperly or | ||||
| 78 | # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations. | ||||
| 79 | class ConfigurationError < ActiveRecordError | ||||
| 5b9b904f » | dhh | 2005-07-10 | 80 | end | |
| 73673256 » | jeremy | 2007-12-09 | 81 | ||
| 82 | # Raised on attempt to update record that is instantiated as read only. | ||||
| 83 | class ReadOnlyRecord < ActiveRecordError | ||||
| 64fcb752 » | jeremy | 2005-10-14 | 84 | end | |
| 73673256 » | jeremy | 2007-12-09 | 85 | ||
| 98dc5827 » | lifo | 2008-05-25 | 86 | # Used by Active Record transaction mechanism to distinguish rollback from other exceptional situations. | |
| 73673256 » | jeremy | 2007-12-09 | 87 | # You can use it to roll your transaction back explicitly in the block passed to +transaction+ method. | |
| 88 | class Rollback < ActiveRecordError | ||||
| 5b2e8b1e » | technoweenie | 2007-10-05 | 89 | end | |
| 73673256 » | jeremy | 2007-12-09 | 90 | ||
| 98dc5827 » | lifo | 2008-05-25 | 91 | # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods). | |
| 73673256 » | jeremy | 2007-12-09 | 92 | class DangerousAttributeError < ActiveRecordError | |
| ebbe4fb0 » | NZKoz | 2007-05-17 | 93 | end | |
| 84a14f26 » | jeremy | 2007-10-07 | 94 | ||
| dc4eec11 » | lifo | 2008-05-09 | 95 | # Raised when you've tried to access a column which wasn't loaded by your finder. | |
| 96 | # Typically this is because <tt>:select</tt> has been specified. | ||||
| 5b801b59 » | NZKoz | 2007-08-14 | 97 | class MissingAttributeError < NoMethodError | |
| 98 | end | ||||
| e48b062e » | jeremy | 2007-05-17 | 99 | ||
| dc4eec11 » | lifo | 2008-05-09 | 100 | # Raised when an error occured while doing a mass assignment to an attribute through the | |
| 101 | # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the | ||||
| 102 | # offending attribute. | ||||
| 103 | class AttributeAssignmentError < ActiveRecordError | ||||
| d2fefbe9 » | dhh | 2005-03-06 | 104 | attr_reader :exception, :attribute | |
| 105 | def initialize(message, exception, attribute) | ||||
| 106 | @exception = exception | ||||
| 107 | @attribute = attribute | ||||
| 108 | @message = message | ||||
| 109 | end | ||||
| 110 | end | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 111 | ||
| dc4eec11 » | lifo | 2008-05-09 | 112 | # Raised when there are multiple errors while doing a mass assignment through the +attributes+ | |
| 113 | # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError | ||||
| 114 | # objects, each corresponding to the error while assigning to an attribute. | ||||
| 115 | class MultiparameterAssignmentErrors < ActiveRecordError | ||||
| d2fefbe9 » | dhh | 2005-03-06 | 116 | attr_reader :errors | |
| 117 | def initialize(errors) | ||||
| 118 | @errors = errors | ||||
| 119 | end | ||||
| 120 | end | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 121 | ||
| 2948910b » | Marcel Molina | 2005-10-10 | 122 | # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with | |
| db045dbb » | dhh | 2004-11-23 | 123 | # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change | |
| 124 | # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 125 | # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones. | |
| 126 | # | ||||
| db045dbb » | dhh | 2004-11-23 | 127 | # See the mapping rules in table_name and the full example in link:files/README.html for more insight. | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 128 | # | |
| db045dbb » | dhh | 2004-11-23 | 129 | # == Creation | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 130 | # | |
| 2948910b » | Marcel Molina | 2005-10-10 | 131 | # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when | |
| 7143d801 » | Marcel Molina | 2007-11-07 | 132 | # you're receiving the data from somewhere else, like an HTTP request. It works like this: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 133 | # | |
| 0591c53e » | dhh | 2005-04-17 | 134 | # user = User.new(:name => "David", :occupation => "Code Artist") | |
| db045dbb » | dhh | 2004-11-23 | 135 | # user.name # => "David" | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 136 | # | |
| db045dbb » | dhh | 2004-11-23 | 137 | # You can also use block initialization: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 138 | # | |
| db045dbb » | dhh | 2004-11-23 | 139 | # user = User.new do |u| | |
| 140 | # u.name = "David" | ||||
| 141 | # u.occupation = "Code Artist" | ||||
| 142 | # end | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 143 | # | |
| db045dbb » | dhh | 2004-11-23 | 144 | # And of course you can just create a bare object and specify the attributes after the fact: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 145 | # | |
| db045dbb » | dhh | 2004-11-23 | 146 | # user = User.new | |
| 147 | # user.name = "David" | ||||
| 148 | # user.occupation = "Code Artist" | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 149 | # | |
| db045dbb » | dhh | 2004-11-23 | 150 | # == Conditions | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 151 | # | |
| c5ec16e5 » | dhh | 2006-06-03 | 152 | # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement. | |
| db045dbb » | dhh | 2004-11-23 | 153 | # The array form is to be used when the condition input is tainted and requires sanitization. The string form can | |
| c5ec16e5 » | dhh | 2006-06-03 | 154 | # be used for statements that don't involve tainted data. The hash form works much like the array form, except | |
| 28767075 » | jeremy | 2007-01-10 | 155 | # only equality and range is possible. Examples: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 156 | # | |
| 48052d70 » | jeremy | 2006-06-02 | 157 | # class User < ActiveRecord::Base | |
| db045dbb » | dhh | 2004-11-23 | 158 | # def self.authenticate_unsafely(user_name, password) | |
| 3dfa56cc » | dhh | 2005-06-26 | 159 | # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'") | |
| db045dbb » | dhh | 2004-11-23 | 160 | # end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 161 | # | |
| db045dbb » | dhh | 2004-11-23 | 162 | # def self.authenticate_safely(user_name, password) | |
| 3dfa56cc » | dhh | 2005-06-26 | 163 | # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ]) | |
| db045dbb » | dhh | 2004-11-23 | 164 | # end | |
| c5ec16e5 » | dhh | 2006-06-03 | 165 | # | |
| 166 | # def self.authenticate_safely_simply(user_name, password) | ||||
| 167 | # find(:first, :conditions => { :user_name => user_name, :password => password }) | ||||
| 168 | # end | ||||
| db045dbb » | dhh | 2004-11-23 | 169 | # end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 170 | # | |
| 2575b3b0 » | dhh | 2004-12-06 | 171 | # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection | |
| 7143d801 » | Marcel Molina | 2007-11-07 | 172 | # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and | |
| 73673256 » | jeremy | 2007-12-09 | 173 | # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, | |
| c5ec16e5 » | dhh | 2006-06-03 | 174 | # which will ensure that an attacker can't escape the query and fake the login (or worse). | |
| 2575b3b0 » | dhh | 2004-12-06 | 175 | # | |
| 5cd38ca2 » | dhh | 2005-03-27 | 176 | # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 177 | # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing | |
| 5cd38ca2 » | dhh | 2005-03-27 | 178 | # the question marks with symbols and supplying a hash with values for the matching symbol keys: | |
| 179 | # | ||||
| a7e6e009 » | Marcel Molina | 2007-12-05 | 180 | # Company.find(:first, :conditions => [ | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 181 | # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date", | |
| 5cd38ca2 » | dhh | 2005-03-27 | 182 | # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' } | |
| 183 | # ]) | ||||
| 184 | # | ||||
| c5ec16e5 » | dhh | 2006-06-03 | 185 | # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND | |
| 186 | # operator. For instance: | ||||
| 187 | # | ||||
| 188 | # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 }) | ||||
| 189 | # Student.find(:all, :conditions => params[:student]) | ||||
| 190 | # | ||||
| 28767075 » | jeremy | 2007-01-10 | 191 | # A range may be used in the hash to use the SQL BETWEEN operator: | |
| 192 | # | ||||
| 193 | # Student.find(:all, :conditions => { :grade => 9..12 }) | ||||
| c5ec16e5 » | dhh | 2006-06-03 | 194 | # | |
| aa4af60a » | lifo | 2008-04-04 | 195 | # An array may be used in the hash to use the SQL IN operator: | |
| 196 | # | ||||
| 197 | # Student.find(:all, :conditions => { :grade => [9,11,12] }) | ||||
| 198 | # | ||||
| db045dbb » | dhh | 2004-11-23 | 199 | # == Overwriting default accessors | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 200 | # | |
| 7143d801 » | Marcel Molina | 2007-11-07 | 201 | # All column values are automatically available through basic accessors on the Active Record object, but sometimes you | |
| 202 | # want to specialize this behavior. This can be done by overwriting the default accessors (using the same | ||||
| 98dc5827 » | lifo | 2008-05-25 | 203 | # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things. | |
| db045dbb » | dhh | 2004-11-23 | 204 | # Example: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 205 | # | |
| db045dbb » | dhh | 2004-11-23 | 206 | # class Song < ActiveRecord::Base | |
| 207 | # # Uses an integer of seconds to hold the length of the song | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 208 | # | |
| db045dbb » | dhh | 2004-11-23 | 209 | # def length=(minutes) | |
| 64092de2 » | fxn | 2008-05-02 | 210 | # write_attribute(:length, minutes.to_i * 60) | |
| db045dbb » | dhh | 2004-11-23 | 211 | # end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 212 | # | |
| db045dbb » | dhh | 2004-11-23 | 213 | # def length | |
| 0591c53e » | dhh | 2005-04-17 | 214 | # read_attribute(:length) / 60 | |
| db045dbb » | dhh | 2004-11-23 | 215 | # end | |
| 216 | # end | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 217 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 218 | # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and | |
| 219 | # <tt>read_attribute(:attribute)</tt> as a shorter form. | ||||
| 0591c53e » | dhh | 2005-04-17 | 220 | # | |
| e4d845ef » | Marcel Molina | 2007-12-05 | 221 | # == Attribute query methods | |
| 222 | # | ||||
| 223 | # In addition to the basic accessors, query methods are also automatically available on the Active Record object. | ||||
| 224 | # Query methods allow you to test whether an attribute value is present. | ||||
| 73673256 » | jeremy | 2007-12-09 | 225 | # | |
| e4d845ef » | Marcel Molina | 2007-12-05 | 226 | # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call | |
| 227 | # to determine whether the user has a name: | ||||
| 228 | # | ||||
| 229 | # user = User.new(:name => "David") | ||||
| 230 | # user.name? # => true | ||||
| 231 | # | ||||
| 232 | # anonymous = User.new(:name => "") | ||||
| 233 | # anonymous.name? # => false | ||||
| 234 | # | ||||
| 2948910b » | Marcel Molina | 2005-10-10 | 235 | # == Accessing attributes before they have been typecasted | |
| 4eab3758 » | dhh | 2005-02-23 | 236 | # | |
| 2948910b » | Marcel Molina | 2005-10-10 | 237 | # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. | |
| dc4eec11 » | lifo | 2008-05-09 | 238 | # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model | |
| 98dc5827 » | lifo | 2008-05-25 | 239 | # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>. | |
| 4eab3758 » | dhh | 2005-02-23 | 240 | # | |
| 241 | # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display | ||||
| 2948910b » | Marcel Molina | 2005-10-10 | 242 | # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you | |
| 4eab3758 » | dhh | 2005-02-23 | 243 | # want. | |
| 244 | # | ||||
| ac8fd7df » | dhh | 2005-01-02 | 245 | # == Dynamic attribute-based finders | |
| 246 | # | ||||
| a5a82d97 » | dhh | 2005-11-04 | 247 | # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by | |
| 98dc5827 » | lifo | 2008-05-25 | 248 | # appending the name of an attribute to <tt>find_by_</tt> or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>, | |
| 249 | # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing | ||||
| a7e6e009 » | Marcel Molina | 2007-12-05 | 250 | # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>. | |
| 251 | # And instead of writing <tt>Person.find(:all, :conditions => ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>. | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 252 | # | |
| ac8fd7df » | dhh | 2005-01-02 | 253 | # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like | |
| 254 | # <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 | ||||
| a7e6e009 » | Marcel Molina | 2007-12-05 | 255 | # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do | |
| ac8fd7df » | dhh | 2005-01-02 | 256 | # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 257 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 258 | # It's even possible to use all the additional parameters to find. For example, the full interface for <tt>Payment.find_all_by_amount</tt> | |
| 259 | # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is | ||||
| 64092de2 » | fxn | 2008-05-02 | 260 | # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>. | |
| 959f362a » | dhh | 2005-01-02 | 261 | # | |
| a5a82d97 » | dhh | 2005-11-04 | 262 | # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with | |
| 5c47ceb3 » | NZKoz | 2008-03-25 | 263 | # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example: | |
| a5a82d97 » | dhh | 2005-11-04 | 264 | # | |
| 265 | # # No 'Summer' tag exists | ||||
| 266 | # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") | ||||
| 73673256 » | jeremy | 2007-12-09 | 267 | # | |
| a5a82d97 » | dhh | 2005-11-04 | 268 | # # Now the 'Summer' tag does exist | |
| 269 | # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") | ||||
| 270 | # | ||||
| c10b2255 » | dhh | 2008-03-25 | 271 | # # Now 'Bob' exist and is an 'admin' | |
| 272 | # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true } | ||||
| 273 | # | ||||
| 274 | # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be setted unless they are given in a block. For example: | ||||
| d19e4642 » | sstephenson | 2006-06-20 | 275 | # | |
| 276 | # # No 'Winter' tag exists | ||||
| 277 | # winter = Tag.find_or_initialize_by_name("Winter") | ||||
| 85fbb22f » | dhh | 2006-09-05 | 278 | # winter.new_record? # true | |
| d19e4642 » | sstephenson | 2006-06-20 | 279 | # | |
| 14cc8d2f » | jeremy | 2007-03-13 | 280 | # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of | |
| 281 | # a list of parameters. For example: | ||||
| 282 | # | ||||
| 283 | # Tag.find_or_create_by_name(:name => "rails", :creator => current_user) | ||||
| 284 | # | ||||
| 285 | # That will either find an existing tag named "rails", or create a new one while setting the user that created it. | ||||
| 286 | # | ||||
| 098fa943 » | dhh | 2005-02-07 | 287 | # == Saving arrays, hashes, and other non-mappable objects in text columns | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 288 | # | |
| 289 | # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+. | ||||
| 2948910b » | Marcel Molina | 2005-10-10 | 290 | # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 291 | # | |
| db045dbb » | dhh | 2004-11-23 | 292 | # class User < ActiveRecord::Base | |
| 293 | # serialize :preferences | ||||
| 294 | # end | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 295 | # | |
| ca2eb16b » | Marcel Molina | 2006-04-26 | 296 | # user = User.create(:preferences => { "background" => "black", "display" => large }) | |
| db045dbb » | dhh | 2004-11-23 | 297 | # User.find(user.id).preferences # => { "background" => "black", "display" => large } | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 298 | # | |
| 2948910b » | Marcel Molina | 2005-10-10 | 299 | # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a | |
| db045dbb » | dhh | 2004-11-23 | 300 | # descendent of a class not in the hierarchy. Example: | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 301 | # | |
| db045dbb » | dhh | 2004-11-23 | 302 | # class User < ActiveRecord::Base | |
| 66f44e6c » | dhh | 2005-01-25 | 303 | # serialize :preferences, Hash | |
| db045dbb » | dhh | 2004-11-23 | 304 | # end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 305 | # | |
| 0591c53e » | dhh | 2005-04-17 | 306 | # user = User.create(:preferences => %w( one two three )) | |
| db045dbb » | dhh | 2004-11-23 | 307 | # User.find(user.id).preferences # raises SerializationTypeMismatch | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 308 | # | |
| db045dbb » | dhh | 2004-11-23 | 309 | # == Single table inheritance | |
| 310 | # | ||||
| 7143d801 » | Marcel Molina | 2007-11-07 | 311 | # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed | |
| db045dbb » | dhh | 2004-11-23 | 312 | # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this: | |
| 313 | # | ||||
| 314 | # class Company < ActiveRecord::Base; end | ||||
| 315 | # class Firm < Company; end | ||||
| 316 | # class Client < Company; end | ||||
| 317 | # class PriorityClient < Client; end | ||||
| 318 | # | ||||
| 98dc5827 » | lifo | 2008-05-25 | 319 | # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then | |
| 320 | # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object. | ||||
| db045dbb » | dhh | 2004-11-23 | 321 | # | |
| f033833f » | dhh | 2004-12-16 | 322 | # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just | |
| 323 | # like normal subclasses with no special magic for differentiating between them or reloading the right type with find. | ||||
| 324 | # | ||||
| db045dbb » | dhh | 2004-11-23 | 325 | # Note, all the attributes for all the cases are kept in the same table. Read more: | |
| 326 | # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 327 | # | |
| db045dbb » | dhh | 2004-11-23 | 328 | # == Connection to multiple databases in different models | |
| 329 | # | ||||
| 330 | # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 331 | # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. | |
| 98dc5827 » | lifo | 2008-05-25 | 332 | # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt> | |
| 333 | # and Course and all of its subclasses will use this connection instead. | ||||
| db045dbb » | dhh | 2004-11-23 | 334 | # | |
| 335 | # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is | ||||
| 336 | # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool. | ||||
| 337 | # | ||||
| 338 | # == Exceptions | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 339 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 340 | # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record. | |
| 341 | # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an | ||||
| db045dbb » | dhh | 2004-11-23 | 342 | # <tt>:adapter</tt> key. | |
| dc4eec11 » | lifo | 2008-05-09 | 343 | # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 344 | # (or a bad spelling of an existing one). | |
| dc4eec11 » | lifo | 2008-05-09 | 345 | # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition. | |
| 346 | # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter. | ||||
| 347 | # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying. | ||||
| 348 | # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist | ||||
| 349 | # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal | ||||
| 350 | # nothing was found, please check its documentation for further details. | ||||
| 351 | # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message. | ||||
| 352 | # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the | ||||
| 353 | # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError | ||||
| d2fefbe9 » | dhh | 2005-03-06 | 354 | # objects that should be inspected to determine which attributes triggered the errors. | |
| dc4eec11 » | lifo | 2008-05-09 | 355 | # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method. | |
| d2fefbe9 » | dhh | 2005-03-06 | 356 | # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. | |
| 57070277 » | dhh | 2005-09-11 | 357 | # | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 358 | # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level). | |
| dc4eec11 » | lifo | 2008-05-09 | 359 | # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all | |
| db045dbb » | dhh | 2004-11-23 | 360 | # instances in the current object space. | |
| 361 | class Base | ||||
| 362 | # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed | ||||
| 363 | # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+. | ||||
| 1a11bffd » | technoweenie | 2007-01-27 | 364 | cattr_accessor :logger, :instance_writer => false | |
| e6941149 » | jeremy | 2007-09-13 | 365 | ||
| db045dbb » | dhh | 2004-11-23 | 366 | def self.inherited(child) #:nodoc: | |
| 367 | @@subclasses[self] ||= [] | ||||
| 368 | @@subclasses[self] << child | ||||
| 369 | super | ||||
| 370 | end | ||||
| e6941149 » | jeremy | 2007-09-13 | 371 | ||
| fed7d334 » | dhh | 2006-03-27 | 372 | def self.reset_subclasses #:nodoc: | |
| bfbf6bba » | jamis | 2005-10-15 | 373 | nonreloadables = [] | |
| e7f61eab » | jamis | 2005-10-15 | 374 | subclasses.each do |klass| | |
| 74165eb6 » | seckar | 2006-08-08 | 375 | unless Dependencies.autoloaded? klass | |
| bfbf6bba » | jamis | 2005-10-15 | 376 | nonreloadables << klass | |
| 377 | next | ||||
| 378 | end | ||||
| e7f61eab » | jamis | 2005-10-15 | 379 | klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) } | |
| 380 | klass.instance_methods(false).each { |m| klass.send :undef_method, m } | ||||
| 381 | end | ||||
| bfbf6bba » | jamis | 2005-10-15 | 382 | @@subclasses = {} | |
| 383 | nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass } | ||||
| 3c0129af » | dhh | 2005-09-20 | 384 | end | |
| 385 | |||||
| db045dbb » | dhh | 2004-11-23 | 386 | @@subclasses = {} | |
| c4a36349 » | jeremy | 2005-06-12 | 387 | ||
| 1a11bffd » | technoweenie | 2007-01-27 | 388 | cattr_accessor :configurations, :instance_writer => false | |
| c4a36349 » | jeremy | 2005-06-12 | 389 | @@configurations = {} | |
| 390 | |||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 391 | # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and | |
| db045dbb » | dhh | 2004-11-23 | 392 | # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as | |
| 393 | # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 394 | # that this is a global setting for all Active Records. | |
| 1a11bffd » | technoweenie | 2007-01-27 | 395 | cattr_accessor :primary_key_prefix_type, :instance_writer => false | |
| db045dbb » | dhh | 2004-11-23 | 396 | @@primary_key_prefix_type = nil | |
| 397 | |||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 398 | # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all | |
| 098fa943 » | dhh | 2005-02-07 | 399 | # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace | |
| db045dbb » | dhh | 2004-11-23 | 400 | # for tables in a shared database. By default, the prefix is the empty string. | |
| 1a11bffd » | technoweenie | 2007-01-27 | 401 | cattr_accessor :table_name_prefix, :instance_writer => false | |
| db045dbb » | dhh | 2004-11-23 | 402 | @@table_name_prefix = "" | |
| 403 | |||||
| 404 | # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", | ||||
| 405 | # "people_basecamp"). By default, the suffix is the empty string. | ||||
| 1a11bffd » | technoweenie | 2007-01-27 | 406 | cattr_accessor :table_name_suffix, :instance_writer => false | |
| db045dbb » | dhh | 2004-11-23 | 407 | @@table_name_suffix = "" | |
| 408 | |||||
| 84a14f26 » | jeremy | 2007-10-07 | 409 | # Indicates whether table names should be the pluralized versions of the corresponding class names. | |
| 98dc5827 » | lifo | 2008-05-25 | 410 | # If true, the default table name for a Product class will be +products+. If false, it would just be +product+. | |
| db045dbb » | dhh | 2004-11-23 | 411 | # See table_name for the full rules on table/class naming. This is true, by default. | |
| 1a11bffd » | technoweenie | 2007-01-27 | 412 | cattr_accessor :pluralize_table_names, :instance_writer => false | |
| db045dbb » | dhh | 2004-11-23 | 413 | @@pluralize_table_names = true | |
| 414 | |||||
| 84a14f26 » | jeremy | 2007-10-07 | 415 | # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors | |
| 2948910b » | Marcel Molina | 2005-10-10 | 416 | # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but | |
| 911614df » | dhh | 2005-03-06 | 417 | # may complicate matters if you use software like syslog. This is true, by default. | |
| 1a11bffd » | technoweenie | 2007-01-27 | 418 | cattr_accessor :colorize_logging, :instance_writer => false | |
| 911614df » | dhh | 2005-03-06 | 419 | @@colorize_logging = true | |
| 420 | |||||
| 60de8c11 » | dhh | 2004-12-28 | 421 | # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database. | |
| 422 | # This is set to :local by default. | ||||
| 1a11bffd » | technoweenie | 2007-01-27 | 423 | cattr_accessor :default_timezone, :instance_writer => false | |
| 60de8c11 » | dhh | 2004-12-28 | 424 | @@default_timezone = :local | |
| d8641ca3 » | jeremy | 2006-03-01 | 425 | ||
| 84a14f26 » | jeremy | 2007-10-07 | 426 | # Determines whether to use a connection for each thread, or a single shared connection for all threads. | |
| 1c66ece2 » | jeremy | 2008-04-28 | 427 | # Defaults to false. If you're writing a threaded application, set to true | |
| 428 | # and periodically call verify_active_connections! to clear out connections | ||||
| 429 | # assigned to stale threads. | ||||
| 1a11bffd » | technoweenie | 2007-01-27 | 430 | cattr_accessor :allow_concurrency, :instance_writer => false | |
| 25fb2db4 » | jeremy | 2006-03-13 | 431 | @@allow_concurrency = false | |
| d8641ca3 » | jeremy | 2006-03-01 | 432 | ||
| 24c3599c » | sstephenson | 2005-10-12 | 433 | # Specifies the format to use when dumping the database schema with Rails' | |
| 434 | # Rakefile. If :sql, the schema is dumped as (potentially database- | ||||
| 73673256 » | jeremy | 2007-12-09 | 435 | # specific) SQL statements. If :ruby, the schema is dumped as an | |
| 24c3599c » | sstephenson | 2005-10-12 | 436 | # ActiveRecord::Schema file which can be loaded into any database that | |
| 437 | # supports migrations. Use :ruby if you want to have different database | ||||
| 438 | # adapters for, e.g., your development and test environments. | ||||
| 1a11bffd » | technoweenie | 2007-01-27 | 439 | cattr_accessor :schema_format , :instance_writer => false | |
| 660952e5 » | dhh | 2006-02-26 | 440 | @@schema_format = :ruby | |
| 3b0e1d90 » | josh | 2008-05-14 | 441 | ||
| bca8751e » | divoxx | 2008-04-11 | 442 | # Determine whether to store the full constant name including namespace when using STI | |
| 443 | superclass_delegating_accessor :store_full_sti_class | ||||
| 444 | self.store_full_sti_class = false | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 445 | ||
| db045dbb » | dhh | 2004-11-23 | 446 | class << self # Class methods | |
| d5a4d5ab » | dhh | 2008-03-12 | 447 | # Find operates with four different retrieval approaches: | |
| 76690111 » | dhh | 2005-04-17 | 448 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 449 | # * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). | |
| 76690111 » | dhh | 2005-04-17 | 450 | # If no record can be found for all of the listed ids, then RecordNotFound will be raised. | |
| 98dc5827 » | lifo | 2008-05-25 | 451 | # * Find first - This will return the first record matched by the options used. These options can either be specific | |
| 452 | # conditions or merely an order. If no record can be matched, +nil+ is returned. Use | ||||
| 453 | # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>. | ||||
| 454 | # * Find last - This will return the last record matched by the options used. These options can either be specific | ||||
| 455 | # conditions or merely an order. If no record can be matched, +nil+ is returned. Use | ||||
| 456 | # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>. | ||||
| 457 | # * Find all - This will return all the records matched by the options used. | ||||
| 458 | # If no records are found, an empty array is returned. Use | ||||
| 459 | # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>. | ||||
| 460 | # | ||||
| 461 | # All approaches accept an options hash as their last parameter. | ||||
| 462 | # | ||||
| 463 | # ==== Attributes | ||||
| 464 | # | ||||
| 465 | # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or <tt>[ "user_name = ?", username ]</tt>. See conditions in the intro. | ||||
| 466 | # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name". | ||||
| 467 | # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause. | ||||
| 468 | # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned. | ||||
| 469 | # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4. | ||||
| 470 | # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) | ||||
| 471 | # or named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s). | ||||
| 9661395d » | Marcel Molina | 2007-12-13 | 472 | # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns. | |
| 64092de2 » | fxn | 2008-05-02 | 473 | # Pass <tt>:readonly => false</tt> to override. | |
| 98dc5827 » | lifo | 2008-05-25 | 474 | # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer | |
| 515886a5 » | dhh | 2005-04-18 | 475 | # to already defined associations. See eager loading under Associations. | |
| 98dc5827 » | lifo | 2008-05-25 | 476 | # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you, for example, want to do a join but not | |
| 6f05696c » | dhh | 2005-07-14 | 477 | # include the joined columns. | |
| 98dc5827 » | lifo | 2008-05-25 | 478 | # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name | |
| 73673256 » | jeremy | 2007-12-09 | 479 | # of a database view). | |
| 98dc5827 » | lifo | 2008-05-25 | 480 | # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated. | |
| 481 | # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE". | ||||
| 64092de2 » | fxn | 2008-05-02 | 482 | # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE". | |
| 76690111 » | dhh | 2005-04-17 | 483 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 484 | # ==== Examples | |
| 485 | # | ||||
| 486 | # # find by id | ||||
| db045dbb » | dhh | 2004-11-23 | 487 | # Person.find(1) # returns the object for ID = 1 | |
| 488 | # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6) | ||||
| 489 | # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17) | ||||
| 7143d801 » | Marcel Molina | 2007-11-07 | 490 | # Person.find([1]) # returns an array for the object with ID = 1 | |
| 515886a5 » | dhh | 2005-04-18 | 491 | # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") | |
| 492 | # | ||||
| 1e9e198c » | jeremy | 2007-03-06 | 493 | # Note that returned records may not be in the same order as the ids you | |
| 64092de2 » | fxn | 2008-05-02 | 494 | # provide since database rows are unordered. Give an explicit <tt>:order</tt> | |
| 1e9e198c » | jeremy | 2007-03-06 | 495 | # to ensure the results are sorted. | |
| 496 | # | ||||
| 98dc5827 » | lifo | 2008-05-25 | 497 | # ==== Examples | |
| 498 | # | ||||
| 499 | # # find first | ||||
| 7d010055 » | dhh | 2005-04-18 | 500 | # Person.find(:first) # returns the first object fetched by SELECT * FROM people | |
| 515886a5 » | dhh | 2005-04-18 | 501 | # Person.find(:first, :conditions => [ "user_name = ?", user_name]) | |
| 502 | # Person.find(:first, :order => "created_on DESC", :offset => 5) | ||||
| 503 | # | ||||
| 98dc5827 » | lifo | 2008-05-25 | 504 | # # find last | |
| d5a4d5ab » | dhh | 2008-03-12 | 505 | # Person.find(:last) # returns the last object fetched by SELECT * FROM people | |
| 506 | # Person.find(:last, :conditions => [ "user_name = ?", user_name]) | ||||
| 507 | # Person.find(:last, :order => "created_on DESC", :offset => 5) | ||||
| 508 | # | ||||
| 98dc5827 » | lifo | 2008-05-25 | 509 | # # find all | |
| 7d010055 » | dhh | 2005-04-18 | 510 | # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people | |
| 515886a5 » | dhh | 2005-04-18 | 511 | # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) | |
| aa4af60a » | lifo | 2008-04-04 | 512 | # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] } | |
| 515886a5 » | dhh | 2005-04-18 | 513 | # Person.find(:all, :offset => 10, :limit => 10) | |
| 514 | # Person.find(:all, :include => [ :account, :friends ]) | ||||
| 33092681 » | jeremy | 2005-11-10 | 515 | # Person.find(:all, :group => "category") | |
| 15aa6e05 » | jeremy | 2006-06-19 | 516 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 517 | # Example for find with a lock: Imagine two concurrent transactions: | |
| 518 | # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting | ||||
| 519 | # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second | ||||
| 15aa6e05 » | jeremy | 2006-06-19 | 520 | # transaction has to wait until the first is finished; we get the | |
| 98dc5827 » | lifo | 2008-05-25 | 521 | # expected <tt>person.visits == 4</tt>. | |
| 522 | # | ||||
| 15aa6e05 » | jeremy | 2006-06-19 | 523 | # Person.transaction do | |
| 524 | # person = Person.find(1, :lock => true) | ||||
| 525 | # person.visits += 1 | ||||
| 526 | # person.save! | ||||
| 527 | # end | ||||
| 6bd672eb » | dhh | 2005-01-01 | 528 | def find(*args) | |
| edd68a58 » | dhh | 2007-07-24 | 529 | options = args.extract_options! | |
| c9c18520 » | dhh | 2006-03-27 | 530 | validate_find_options(options) | |
| 531 | set_readonly_option!(options) | ||||
| 64fcb752 » | jeremy | 2005-10-14 | 532 | ||
| abc895b8 » | dhh | 2005-04-03 | 533 | case args.first | |
| c9c18520 » | dhh | 2006-03-27 | 534 | when :first then find_initial(options) | |
| d5a4d5ab » | dhh | 2008-03-12 | 535 | when :last then find_last(options) | |
| c9c18520 » | dhh | 2006-03-27 | 536 | when :all then find_every(options) | |
| 537 | else find_from_ids(args, options) | ||||
| db045dbb » | dhh | 2004-11-23 | 538 | end | |
| 539 | end | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 540 | ||
| 98dc5827 » | lifo | 2008-05-25 | 541 | # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the | |
| 542 | # same arguments to this method as you can to <tt>find(:first)</tt>. | ||||
| c6f2af5c » | dhh | 2008-03-24 | 543 | def first(*args) | |
| 544 | find(:first, *args) | ||||
| 545 | end | ||||
| 73673256 » | jeremy | 2007-12-09 | 546 | ||
| 98dc5827 » | lifo | 2008-05-25 | 547 | # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the | |
| 548 | # same arguments to this method as you can to <tt>find(:last)</tt>. | ||||
| c6f2af5c » | dhh | 2008-03-24 | 549 | def last(*args) | |
| 550 | find(:last, *args) | ||||
| 551 | end | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 552 | ||
| 0a6980f2 » | David Heinemeier Hansson | 2008-04-28 | 553 | # This is an alias for find(:all). You can pass in all the same arguments to this method as you can | |
| 554 | # to find(:all) | ||||
| 555 | def all(*args) | ||||
| 556 | find(:all, *args) | ||||
| 557 | end | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 558 | ||
| 98dc5827 » | lifo | 2008-05-25 | 559 | # Executes a custom SQL query against your database and returns all the results. The results will | |
| 73673256 » | jeremy | 2007-12-09 | 560 | # be returned as an array with columns requested encapsulated as attributes of the model you call | |
| 561 | # this method from. If you call +Product.find_by_sql+ then the results will be returned in a Product | ||||
| edf32cea » | Marcel Molina | 2007-12-05 | 562 | # object with the attributes you specified in the SQL query. | |
| 563 | # | ||||
| 73673256 » | jeremy | 2007-12-09 | 564 | # If you call a complicated SQL query which spans multiple tables the columns specified by the | |
| 565 | # SELECT will be attributes of the model, whether or not they are columns of the corresponding | ||||
| edf32cea » | Marcel Molina | 2007-12-05 | 566 | # table. | |
| 567 | # | ||||
| 98dc5827 » | lifo | 2008-05-25 | 568 | # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be | |
| 73673256 » | jeremy | 2007-12-09 | 569 | # no database agnostic conversions performed. This should be a last resort because using, for example, | |
| 570 | # MySQL specific terms will lock you to using that particular database engine or require you to | ||||
| edf32cea » | Marcel Molina | 2007-12-05 | 571 | # change your call if you switch engines | |
| 572 | # | ||||
| 573 | # ==== Examples | ||||
| 98dc5827 » | lifo | 2008-05-25 | 574 | # # A simple SQL query spanning multiple tables | |
| edf32cea » | Marcel Molina | 2007-12-05 | 575 | # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" | |
| 576 | # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] | ||||
| 577 | # | ||||
| 578 | # # You can use the same string replacement techniques as you can with ActiveRecord#find | ||||
| 579 | # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] | ||||
| 580 | # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...] | ||||
| db045dbb » | dhh | 2004-11-23 | 581 | def find_by_sql(sql) | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 582 | connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) } | |
| db045dbb » | dhh | 2004-11-23 | 583 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 584 | ||
| 73673256 » | jeremy | 2007-12-09 | 585 | # Checks whether a record exists in the database that matches conditions given. These conditions | |
| 586 | # can either be a single integer representing a primary key id to be found, or a condition to be | ||||
| 971ed153 » | Marcel Molina | 2007-12-05 | 587 | # matched like using ActiveRecord#find. | |
| 588 | # | ||||
| 73673256 » | jeremy | 2007-12-09 | 589 | # The +id_or_conditions+ parameter can be an Integer or a String if you want to search the primary key | |
| 590 | # column of the table for a matching id, or if you're looking to match against a condition you can use | ||||
| 971ed153 » | Marcel Molina | 2007-12-05 | 591 | # an Array or a Hash. | |
| 592 | # | ||||
| 73673256 » | jeremy | 2007-12-09 | 593 | # Possible gotcha: You can't pass in a condition as a string e.g. "name = 'Jamie'", this would be | |
| 971ed153 » | Marcel Molina | 2007-12-05 | 594 | # sanitized and then queried against the primary key column as "id = 'name = \'Jamie" | |
| 595 | # | ||||
| 596 | # ==== Examples | ||||
| abc895b8 » | dhh | 2005-04-03 | 597 | # Person.exists?(5) | |
| 58ebf302 » | jeremy | 2006-08-03 | 598 | # Person.exists?('5') | |
| 8085cbfd » | dhh | 2006-08-03 | 599 | # Person.exists?(:name => "David") | |
| 58ebf302 » | jeremy | 2006-08-03 | 600 | # Person.exists?(['name LIKE ?', "%#{query}%"]) | |
| 601 | def exists?(id_or_conditions) | ||||
| 0ad24df6 » | technoweenie | 2008-01-02 | 602 | connection.select_all( | |
| 603 | construct_finder_sql( | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 604 | :select => "#{quoted_table_name}.#{primary_key}", | |
| 605 | :conditions => expand_id_conditions(id_or_conditions), | ||||
| 0ad24df6 » | technoweenie | 2008-01-02 | 606 | :limit => 1 | |
| 3b0e1d90 » | josh | 2008-05-14 | 607 | ), | |
| 0ad24df6 » | technoweenie | 2008-01-02 | 608 | "#{name} Exists" | |
| 609 | ).size > 0 | ||||
| db045dbb » | dhh | 2004-11-23 | 610 | end | |
| abc895b8 » | dhh | 2005-04-03 | 611 | ||
| 73673256 » | jeremy | 2007-12-09 | 612 | # Creates an object (or multiple objects) and saves it to the database, if validations pass. | |
| a23bea7c » | Marcel Molina | 2007-12-05 | 613 | # The resulting object is returned whether the object was saved successfully to the database or not. | |
| 614 | # | ||||
| 615 | # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the | ||||
| 616 | # attributes on the objects that are to be created. | ||||
| 617 | # | ||||
| 618 | # ==== Examples | ||||
| 619 | # # Create a single new object | ||||
| 620 | # User.create(:first_name => 'Jamie') | ||||
| dd120ede » | dhh | 2008-04-30 | 621 | # | |
| a23bea7c » | Marcel Molina | 2007-12-05 | 622 | # # Create an Array of new objects | |
| dc4eec11 » | lifo | 2008-05-09 | 623 | # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) | |
| dd120ede » | dhh | 2008-04-30 | 624 | # | |
| 625 | # # Create a single object and pass it into a block to set other attributes. | ||||
| 626 | # User.create(:first_name => 'Jamie') do |u| | ||||
| 627 | # u.is_admin = false | ||||
| 628 | # end | ||||
| 629 | # | ||||
| 630 | # # Creating an Array of new objects using a block, where the block is executed for each object: | ||||
| dc4eec11 » | lifo | 2008-05-09 | 631 | # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u| | |
| dd120ede » | dhh | 2008-04-30 | 632 | # u.is_admin = false | |
| 3b0e1d90 » | josh | 2008-05-14 | 633 | # end | |
| dd120ede » | dhh | 2008-04-30 | 634 | def create(attributes = nil, &block) | |
| efa81dad » | dhh | 2005-01-25 | 635 | if attributes.is_a?(Array) | |
| dd120ede » | dhh | 2008-04-30 | 636 | attributes.collect { |attr| create(attr, &block) } | |
| efa81dad » | dhh | 2005-01-25 | 637 | else | |
| 638 | object = new(attributes) | ||||
| dd120ede » | dhh | 2008-04-30 | 639 | yield(object) if block_given? | |
| efa81dad » | dhh | 2005-01-25 | 640 | object.save | |
| 641 | object | ||||
| 642 | end | ||||
| db045dbb » | dhh | 2004-11-23 | 643 | end | |
| 644 | |||||
| 1b7a18de » | Marcel Molina | 2007-12-05 | 645 | # Updates an object (or multiple objects) and saves it to the database, if validations pass. | |
| 646 | # The resulting object is returned whether the object was saved successfully to the database or not. | ||||
| 5e99422d » | dhh | 2006-02-25 | 647 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 648 | # ==== Attributes | |
| 5e99422d » | dhh | 2006-02-25 | 649 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 650 | # * +id+ - This should be the id or an array of ids to be updated. | |
| 651 | # * +attributes+ - This should be a Hash of attributes to be set on the object, or an array of Hashes. | ||||
| 1b7a18de » | Marcel Molina | 2007-12-05 | 652 | # | |
| 653 | # ==== Examples | ||||
| 654 | # | ||||
| 655 | # # Updating one record: | ||||
| dc4eec11 » | lifo | 2008-05-09 | 656 | # Person.update(15, { :user_name => 'Samuel', :group => 'expert' }) | |
| 73673256 » | jeremy | 2007-12-09 | 657 | # | |
| 1b7a18de » | Marcel Molina | 2007-12-05 | 658 | # # Updating multiple records: | |
| dc4eec11 » | lifo | 2008-05-09 | 659 | # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } } | |
| 5e99422d » | dhh | 2006-02-25 | 660 | # Person.update(people.keys, people.values) | |
| db045dbb » | dhh | 2004-11-23 | 661 | def update(id, attributes) | |
| efa81dad » | dhh | 2005-01-25 | 662 | if id.is_a?(Array) | |
| 663 | idx = -1 | ||||
| 8b5f4e47 » | jeremy | 2007-12-22 | 664 | id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) } | |
| efa81dad » | dhh | 2005-01-25 | 665 | else | |
| 666 | object = find(id) | ||||
| 667 | object.update_attributes(attributes) | ||||
| 668 | object | ||||
| 669 | end | ||||
| db045dbb » | dhh | 2004-11-23 | 670 | end | |
| 671 | |||||
| 6a45e01b » | Marcel Molina | 2007-12-05 | 672 | # Delete an object (or multiple objects) where the +id+ given matches the primary_key. A SQL +DELETE+ command | |
| 673 | # is executed on the database which means that no callbacks are fired off running this. This is an efficient method | ||||
| 674 | # of deleting records that don't need cleaning up after or other actions to be taken. | ||||
| 73673256 » | jeremy | 2007-12-09 | 675 | # | |
| 6a45e01b » | Marcel Molina | 2007-12-05 | 676 | # Objects are _not_ instantiated with this method. | |
| 677 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 678 | # ==== Attributes | |
| 73673256 » | jeremy | 2007-12-09 | 679 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 680 | # * +id+ - Can be either an Integer or an Array of Integers. | |
| 6a45e01b » | Marcel Molina | 2007-12-05 | 681 | # | |
| 682 | # ==== Examples | ||||
| 683 | # | ||||
| 684 | # # Delete a single object | ||||
| 685 | # Todo.delete(1) | ||||
| 73673256 » | jeremy | 2007-12-09 | 686 | # | |
| 6a45e01b » | Marcel Molina | 2007-12-05 | 687 | # # Delete multiple objects | |
| 688 | # todos = [1,2,3] | ||||
| 689 | # Todo.delete(todos) | ||||
| 648b8fda » | dhh | 2004-12-17 | 690 | def delete(id) | |
| 98165fd3 » | jeremy | 2007-03-08 | 691 | delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ]) | |
| 648b8fda » | dhh | 2004-12-17 | 692 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 693 | ||
| ed69b38a » | Marcel Molina | 2007-12-05 | 694 | # Destroy an object (or multiple objects) that has the given id, the object is instantiated first, | |
| 695 | # therefore all callbacks and filters are fired off before the object is deleted. This method is | ||||
| 696 | # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run. | ||||
| 73673256 » | jeremy | 2007-12-09 | 697 | # | |
| 698 | # This essentially finds the object (or multiple objects) with the given id, creates a new object | ||||
| ed69b38a » | Marcel Molina | 2007-12-05 | 699 | # from the attributes, and then calls destroy on it. | |
| 700 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 701 | # ==== Attributes | |
| 73673256 » | jeremy | 2007-12-09 | 702 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 703 | # * +id+ - Can be either an Integer or an Array of Integers. | |
| ed69b38a » | Marcel Molina | 2007-12-05 | 704 | # | |
| 705 | # ==== Examples | ||||
| 706 | # | ||||
| 707 | # # Destroy a single object | ||||
| 708 | # Todo.destroy(1) | ||||
| 73673256 » | jeremy | 2007-12-09 | 709 | # | |
| ed69b38a » | Marcel Molina | 2007-12-05 | 710 | # # Destroy multiple objects | |
| 711 | # todos = [1,2,3] | ||||
| 712 | # Todo.destroy(todos) | ||||
| 648b8fda » | dhh | 2004-12-17 | 713 | def destroy(id) | |
| 8b5f4e47 » | jeremy | 2007-12-22 | 714 | if id.is_a?(Array) | |
| 715 | id.map { |one_id| destroy(one_id) } | ||||
| 716 | else | ||||
| 717 | find(id).destroy | ||||
| 718 | end | ||||
| 648b8fda » | dhh | 2004-12-17 | 719 | end | |
| 720 | |||||
| 4f1d353b » | Marcel Molina | 2007-12-05 | 721 | # Updates all records with details given if they match a set of conditions supplied, limits and order can | |
| 722 | # also be supplied. | ||||
| a38f28ff » | jeremy | 2007-03-17 | 723 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 724 | # ==== Attributes | |
| 4f1d353b » | Marcel Molina | 2007-12-05 | 725 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 726 | # * +updates+ - A String of column and value pairs that will be set on any records that match conditions. | |
| 727 | # * +conditions+ - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. | ||||
| 728 | # See conditions in the intro for more info. | ||||
| 729 | # * +options+ - Additional options are <tt>:limit</tt> and/or <tt>:order</tt>, see the examples for usage. | ||||
| 4f1d353b » | Marcel Molina | 2007-12-05 | 730 | # | |
| 731 | # ==== Examples | ||||
| 732 | # | ||||
| 733 | # # Update all billing objects with the 3 different attributes given | ||||
| 734 | # Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" ) | ||||
| 73673256 » | jeremy | 2007-12-09 | 735 | # | |
| 4f1d353b » | Marcel Molina | 2007-12-05 | 736 | # # Update records that match our conditions | |
| 737 | # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" ) | ||||
| 738 | # | ||||
| 739 | # # Update records that match our conditions but limit it to 5 ordered by date | ||||
| 73673256 » | jeremy | 2007-12-09 | 740 | # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'", | |
| 4f1d353b » | Marcel Molina | 2007-12-05 | 741 | # :order => 'created_at', :limit => 5 ) | |
| a38f28ff » | jeremy | 2007-03-17 | 742 | def update_all(updates, conditions = nil, options = {}) | |
| ebe3a0d5 » | jeremy | 2008-01-05 | 743 | sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} " | |
| a38f28ff » | jeremy | 2007-03-17 | 744 | scope = scope(:find) | |
| 745 | add_conditions!(sql, conditions, scope) | ||||
| c36f8111 » | jeremy | 2008-01-03 | 746 | add_order!(sql, options[:order], nil) | |
| 747 | add_limit!(sql, options, nil) | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 748 | connection.update(sql, "#{name} Update") | |
| db045dbb » | dhh | 2004-11-23 | 749 | end | |
| 0d2db8a7 » | dhh | 2005-01-24 | 750 | ||
| 4b055a4a » | jeremy | 2007-12-10 | 751 | # Destroys the records matching +conditions+ by instantiating each record and calling the destroy method. | |
| 752 | # This means at least 2*N database queries to destroy N records, so avoid destroy_all if you are deleting | ||||
| 753 | # many records. If you want to simply delete records without worrying about dependent associations or | ||||
| 754 | # callbacks, use the much faster +delete_all+ method instead. | ||||
| 755 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 756 | # ==== Attributes | |
| 4b055a4a » | jeremy | 2007-12-10 | 757 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 758 | # * +conditions+ - Conditions are specified the same way as with +find+ method. | |
| 4b055a4a » | jeremy | 2007-12-10 | 759 | # | |
| 760 | # ==== Example | ||||
| 761 | # | ||||
| db045dbb » | dhh | 2004-11-23 | 762 | # Person.destroy_all "last_login < '2004-04-04'" | |
| 4b055a4a » | jeremy | 2007-12-10 | 763 | # | |
| 764 | # This loads and destroys each person one by one, including its dependent associations and before_ and | ||||
| 765 | # after_destroy callbacks. | ||||
| db045dbb » | dhh | 2004-11-23 | 766 | def destroy_all(conditions = nil) | |
| 3dfa56cc » | dhh | 2005-06-26 | 767 | find(:all, :conditions => conditions).each { |object| object.destroy } | |
| db045dbb » | dhh | 2004-11-23 | 768 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 769 | ||
| 4b055a4a » | jeremy | 2007-12-10 | 770 | # Deletes the records matching +conditions+ without instantiating the records first, and hence not | |
| 771 | # calling the destroy method and invoking callbacks. This is a single SQL query, much more efficient | ||||
| 772 | # than destroy_all. | ||||
| 773 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 774 | # ==== Attributes | |
| 4b055a4a » | jeremy | 2007-12-10 | 775 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 776 | # * +conditions+ - Conditions are specified the same way as with +find+ method. | |
| 4b055a4a » | jeremy | 2007-12-10 | 777 | # | |
| 778 | # ==== Example | ||||
| 779 | # | ||||
| 090bfcec » | jeremy | 2005-11-13 | 780 | # Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')" | |
| 4b055a4a » | jeremy | 2007-12-10 | 781 | # | |
| 782 | # This deletes the affected posts all at once with a single DELETE query. If you need to destroy dependent | ||||
| 783 | # associations or call your before_ or after_destroy callbacks, use the +destroy_all+ method instead. | ||||
| db045dbb » | dhh | 2004-11-23 | 784 | def delete_all(conditions = nil) | |
| 9b6207c3 » | jeremy | 2007-10-15 | 785 | sql = "DELETE FROM #{quoted_table_name} " | |
| c9c18520 » | dhh | 2006-03-27 | 786 | add_conditions!(sql, conditions, scope(:find)) | |
| db045dbb » | dhh | 2004-11-23 | 787 | connection.delete(sql, "#{name} Delete all") | |
| 788 | end | ||||
| 789 | |||||
| 790 | # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. | ||||
| 73673256 » | jeremy | 2007-12-09 | 791 | # The use of this method should be restricted to complicated SQL queries that can't be executed | |
| ee614d63 » | Marcel Molina | 2007-05-05 | 792 | # using the ActiveRecord::Calculations class methods. Look into those before using this. | |
| 793 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 794 | # ==== Attributes | |
| 73673256 » | jeremy | 2007-12-09 | 795 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 796 | # * +sql+ - An SQL statement which should return a count query from the database, see the example below. | |
| ee614d63 » | Marcel Molina | 2007-05-05 | 797 | # | |
| 798 | # ==== Examples | ||||
| 799 | # | ||||
| e17bf818 » | jamis | 2005-08-14 | 800 | # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" | |
| db045dbb » | dhh | 2004-11-23 | 801 | def count_by_sql(sql) | |
| a775cb19 » | dhh | 2004-12-07 | 802 | sql = sanitize_conditions(sql) | |
| caaf40d5 » | dhh | 2005-09-24 | 803 | connection.select_value(sql, "#{name} Count").to_i | |
| db045dbb » | dhh | 2004-11-23 | 804 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 805 | ||
| 83752373 » | jamis | 2007-02-07 | 806 | # A generic "counter updater" implementation, intended primarily to be | |
| 807 | # used by increment_counter and decrement_counter, but which may also | ||||
| 808 | # be useful on its own. It simply does a direct SQL update for the record | ||||
| 809 | # with the given ID, altering the given hash of counters by the amount | ||||
| 810 | # given by the corresponding value: | ||||
| 811 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 812 | # ==== Attributes | |
| 73673256 » | jeremy | 2007-12-09 | 813 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 814 | # * +id+ - The id of the object you wish to update a counter on. | |
| 815 | # * +counters+ - An Array of Hashes containing the names of the fields | ||||
| 816 | # to update as keys and the amount to update the field by as values. | ||||
| 73673256 » | jeremy | 2007-12-09 | 817 | # | |
| 6bd7d30e » | Marcel Molina | 2007-12-05 | 818 | # ==== Examples | |
| 73673256 » | jeremy | 2007-12-09 | 819 | # | |
| 820 | # # For the Post with id of 5, decrement the comment_count by 1, and | ||||
| 6bd7d30e » | Marcel Molina | 2007-12-05 | 821 | # # increment the action_count by 1 | |
| 83752373 » | jamis | 2007-02-07 | 822 | # Post.update_counters 5, :comment_count => -1, :action_count => 1 | |
| 6bd7d30e » | Marcel Molina | 2007-12-05 | 823 | # # Executes the following SQL: | |
| 83752373 » | jamis | 2007-02-07 | 824 | # # UPDATE posts | |
| 825 | # # SET comment_count = comment_count - 1, | ||||
| 826 | # # action_count = action_count + 1 | ||||
| 827 | # # WHERE id = 5 | ||||
| 828 | def update_counters(id, counters) | ||||
| 829 | updates = counters.inject([]) { |list, (counter_name, increment)| | ||||
| 830 | sign = increment < 0 ? "-" : "+" | ||||
| 98165fd3 » | jeremy | 2007-03-08 | 831 | list << "#{connection.quote_column_name(counter_name)} = #{connection.quote_column_name(counter_name)} #{sign} #{increment.abs}" | |
| 83752373 » | jamis | 2007-02-07 | 832 | }.join(", ") | |
| 98165fd3 » | jeremy | 2007-03-08 | 833 | update_all(updates, "#{connection.quote_column_name(primary_key)} = #{quote_value(id)}") | |
| 83752373 » | jamis | 2007-02-07 | 834 | end | |
| 835 | |||||
| 15dc567e » | Marcel Molina | 2007-05-05 | 836 | # Increment a number field by one, usually representing a count. | |
| 837 | # | ||||
| 73673256 » | jeremy | 2007-12-09 | 838 | # This is used for caching aggregate values, so that they don't need to be computed every time. | |
| 839 | # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is | ||||
| 7143d801 » | Marcel Molina | 2007-11-07 | 840 | # shown it would have to run an SQL query to find how many posts and comments there are. | |
| 15dc567e » | Marcel Molina | 2007-05-05 | 841 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 842 | # ==== Attributes | |
| 15dc567e » | Marcel Molina | 2007-05-05 | 843 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 844 | # * +counter_name+ - The name of the field that should be incremented. | |
| 845 | # * +id+ - The id of the object that should be incremented. | ||||
| 15dc567e » | Marcel Molina | 2007-05-05 | 846 | # | |
| 847 | # ==== Examples | ||||
| 848 | # | ||||
| 849 | # # Increment the post_count column for the record with an id of 5 | ||||
| 850 | # DiscussionBoard.increment_counter(:post_count, 5) | ||||
| db045dbb » | dhh | 2004-11-23 | 851 | def increment_counter(counter_name, id) | |
| 83752373 » | jamis | 2007-02-07 | 852 | update_counters(id, counter_name => 1) | |
| db045dbb » | dhh | 2004-11-23 | 853 | end | |
| 854 | |||||
| 5bd35705 » | Marcel Molina | 2007-05-05 | 855 | # Decrement a number field by one, usually representing a count. | |
| 856 | # | ||||
| 857 | # This works the same as increment_counter but reduces the column value by 1 instead of increasing it. | ||||
| 858 | # | ||||
| dc4eec11 » | lifo | 2008-05-09 | 859 | # ==== Attributes | |
| 5bd35705 » | Marcel Molina | 2007-05-05 | 860 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 861 | # * +counter_name+ - The name of the field that should be decremented. | |
| 862 | # * +id+ - The id of the object that should be decremented. | ||||
| 5bd35705 » | Marcel Molina | 2007-05-05 | 863 | # | |
| 864 | # ==== Examples | ||||
| 865 | # | ||||
| 866 | # # Decrement the post_count column for the record with an id of 5 | ||||
| 867 | # DiscussionBoard.decrement_counter(:post_count, 5) | ||||
| db045dbb » | dhh | 2004-11-23 | 868 | def decrement_counter(counter_name, id) | |
| 83752373 » | jamis | 2007-02-07 | 869 | update_counters(id, counter_name => -1) | |
| db045dbb » | dhh | 2004-11-23 | 870 | end | |
| 871 | |||||
| c450a36f » | dhh | 2006-03-05 | 872 | ||
| 98dc5827 » | lifo | 2008-05-25 | 873 | # Attributes named in this macro are protected from mass-assignment, | |
| 874 | # such as <tt>new(attributes)</tt>, | ||||
| 875 | # <tt>update_attributes(attributes)</tt>, or | ||||
| 876 | # <tt>attributes=(attributes)</tt>. | ||||
| 877 | # | ||||
| 878 | # Mass-assignment to these attributes will simply be ignored, to assign | ||||
| 879 | # to them you can use direct writer methods. This is meant to protect | ||||
| 880 | # sensitive attributes from being overwritten by malicious users | ||||
| 881 | # tampering with URLs or forms. | ||||
| db045dbb » | dhh | 2004-11-23 | 882 | # | |
| 883 | # class Customer < ActiveRecord::Base | ||||
| 884 | # attr_protected :credit_rating | ||||
| 885 | # end | ||||
| 886 | # | ||||
| 887 | # customer = Customer.new("name" => David, "credit_rating" => "Excellent") | ||||
| 888 | # customer.credit_rating # => nil | ||||
| 889 | # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" } | ||||
| 890 | # customer.credit_rating # => nil | ||||
| 891 | # | ||||
| 892 | # customer.credit_rating = "Average" | ||||
| 893 | # customer.credit_rating # => "Average" | ||||
| d761ac40 » | Marcel Molina | 2007-10-25 | 894 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 895 | # To start from an all-closed default and enable attributes as needed, | |
| 896 | # have a look at +attr_accessible+. | ||||
| db045dbb » | dhh | 2004-11-23 | 897 | def attr_protected(*attributes) | |
| 3a3e7efe » | jeremy | 2007-11-28 | 898 | write_inheritable_attribute("attr_protected", Set.new(attributes.map(&:to_s)) + (protected_attributes || [])) | |
| db045dbb » | dhh | 2004-11-23 | 899 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 900 | ||
| 098fa943 » | dhh | 2005-02-07 | 901 | # Returns an array of all the attributes that have been protected from mass-assignment. | |
| db045dbb » | dhh | 2004-11-23 | 902 | def protected_attributes # :nodoc: | |
| 903 | read_inheritable_attribute("attr_protected") | ||||
| 904 | end | ||||
| 905 | |||||
| 98dc5827 » | lifo | 2008-05-25 | 906 | # Specifies a white list of model attributes that can be set via | |
| 907 | # mass-assignment, such as <tt>new(attributes)</tt>, | ||||
| 908 | # <tt>update_attributes(attributes)</tt>, or | ||||
| 909 | # <tt>attributes=(attributes)</tt> | ||||
| f770b829 » | Marcel Molina | 2007-11-06 | 910 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 911 | # This is the opposite of the +attr_protected+ macro: Mass-assignment | |
| 912 | # will only set attributes in this list, to assign to the rest of | ||||
| 913 | # attributes you can use direct writer methods. This is meant to protect | ||||
| 914 | # sensitive attributes from being overwritten by malicious users | ||||
| 915 | # tampering with URLs or forms. If you'd rather start from an all-open | ||||
| 916 | # default and restrict attributes as needed, have a look at | ||||
| 917 | # +attr_protected+. | ||||
| d761ac40 » | Marcel Molina | 2007-10-25 | 918 | # | |
| 919 | # class Customer < ActiveRecord::Base | ||||
| f770b829 » | Marcel Molina | 2007-11-06 | 920 | # attr_accessible :name, :nickname | |
| d761ac40 » | Marcel Molina | 2007-10-25 | 921 | # end | |
| 922 | # | ||||
| f770b829 » | Marcel Molina | 2007-11-06 | 923 | # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent") | |
| 924 | # customer.credit_rating # => nil | ||||
| 925 | # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" } | ||||
| 926 | # customer.credit_rating # => nil | ||||
| d761ac40 » | Marcel Molina | 2007-10-25 | 927 | # | |
| f770b829 » | Marcel Molina | 2007-11-06 | 928 | # customer.credit_rating = "Average" | |
| 929 | # customer.credit_rating # => "Average" | ||||
| db045dbb » | dhh | 2004-11-23 | 930 | def attr_accessible(*attributes) | |
| 3a3e7efe » | jeremy | 2007-11-28 | 931 | write_inheritable_attribute("attr_accessible", Set.new(attributes.map(&:to_s)) + (accessible_attributes || [])) | |
| db045dbb » | dhh | 2004-11-23 | 932 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 933 | ||
| 098fa943 » | dhh | 2005-02-07 | 934 | # Returns an array of all the attributes that have been made accessible to mass-assignment. | |
| db045dbb » | dhh | 2004-11-23 | 935 | def accessible_attributes # :nodoc: | |
| 936 | read_inheritable_attribute("attr_accessible") | ||||
| 937 | end | ||||
| 938 | |||||
| 66d05f5e » | technoweenie | 2007-09-30 | 939 | # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards. | |
| 940 | def attr_readonly(*attributes) | ||||
| a33007d3 » | jeremy | 2007-11-28 | 941 | write_inheritable_attribute("attr_readonly", Set.new(attributes.map(&:to_s)) + (readonly_attributes || [])) | |
| 66d05f5e » | technoweenie | 2007-09-30 | 942 | end | |
| 943 | |||||
| 944 | # Returns an array of all the attributes that have been specified as readonly. | ||||
| 945 | def readonly_attributes | ||||
| 946 | read_inheritable_attribute("attr_readonly") | ||||
| 947 | end | ||||
| c450a36f » | dhh | 2006-03-05 | 948 | ||
| 73673256 » | jeremy | 2007-12-09 | 949 | # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, | |
| 950 | # then specify the name of that attribute using this method and it will be handled automatically. | ||||
| 951 | # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that | ||||
| 98dc5827 » | lifo | 2008-05-25 | 952 | # class on retrieval or SerializationTypeMismatch will be raised. | |
| 1a0cdf74 » | dhh | 2007-06-23 | 953 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 954 | # ==== Attributes | |
| 1a0cdf74 » | dhh | 2007-06-23 | 955 | # | |
| dc4eec11 » | lifo | 2008-05-09 | 956 | # * +attr_name+ - The field name that should be serialized. | |
| 957 | # * +class_name+ - Optional, class name that the object type should be equal to. | ||||
| 1a0cdf74 » | dhh | 2007-06-23 | 958 | # | |
| 959 | # ==== Example | ||||
| 960 | # # Serialize a preferences attribute | ||||
| 961 | # class User | ||||
| 962 | # serialize :preferences | ||||
| 963 | # end | ||||
| db045dbb » | dhh | 2004-11-23 | 964 | def serialize(attr_name, class_name = Object) | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 965 | serialized_attributes[attr_name.to_s] = class_name | |
| db045dbb » | dhh | 2004-11-23 | 966 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 967 | ||
| db045dbb » | dhh | 2004-11-23 | 968 | # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values. | |
| 969 | def serialized_attributes | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 970 | read_inheritable_attribute("attr_serialized") or write_inheritable_attribute("attr_serialized", {}) | |
| db045dbb » | dhh | 2004-11-23 | 971 | end | |
| 972 | |||||
| c450a36f » | dhh | 2006-03-05 | 973 | ||
| db045dbb » | dhh | 2004-11-23 | 974 | # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending | |
| 98dc5827 » | lifo | 2008-05-25 | 975 | # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used | |
| d64832c0 » | Marcel Molina | 2007-12-05 | 976 | # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class | |
| 7143d801 » | Marcel Molina | 2007-11-07 | 977 | # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb. | |
| db045dbb » | dhh | 2004-11-23 | 978 | # | |
| 14101c7b » | jeremy | 2006-08-16 | 979 | # Nested classes are given table names prefixed by the singular form of | |
| 98dc5827 » | lifo | 2008-05-25 | 980 | # the parent's table name. Enclosing modules are not considered. | |
| 981 | # | ||||
| 982 | # ==== Examples | ||||
| d64832c0 » | Marcel Molina | 2007-12-05 | 983 | # | |
| 984 | # class Invoice < ActiveRecord::Base; end; | ||||
| 14101c7b » | jeremy | 2006-08-16 | 985 | # file class table_name | |
| 986 | # invoice.rb Invoice invoices | ||||
| d64832c0 » | Marcel Molina | 2007-12-05 | 987 | # | |
| 988 | # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end; | ||||
| 989 | # file class table_name | ||||
| 990 | # invoice.rb Invoice::Lineitem invoice_lineitems | ||||
| 991 | # | ||||
| 992 | # module Invoice; class Lineitem < ActiveRecord::Base; end; end; | ||||
| 993 | # file class table_name | ||||
| 994 | # invoice/lineitem.rb Invoice::Lineitem lineitems | ||||
| db045dbb » | dhh | 2004-11-23 | 995 | # | |
| 98dc5827 » | lifo | 2008-05-25 | 996 | # Additionally, the class-level +table_name_prefix+ is prepended and the | |
| 997 | # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, | ||||
| 14101c7b » | jeremy | 2006-08-16 | 998 | # the table name guess for an Invoice class becomes "myapp_invoices". | |
| 999 | # Invoice::Lineitem becomes "myapp_invoice_lineitems". | ||||
| 1000 | # | ||||
| 1001 | # You can also overwrite this class method to allow for unguessable | ||||
| 1002 | # links, such as a Mouse class with a link to a "mice" table. Example: | ||||
| db045dbb » | dhh | 2004-11-23 | 1003 | # | |
| 1004 | # class Mouse < ActiveRecord::Base | ||||
| 14101c7b » | jeremy | 2006-08-16 | 1005 | # set_table_name "mice" | |
| db045dbb » | dhh | 2004-11-23 | 1006 | # end | |
| dcc48680 » | dhh | 2004-12-22 | 1007 | def table_name | |
| d736568f » | Marcel Molina | 2005-10-10 | 1008 | reset_table_name | |
| 1009 | end | ||||
| 1010 | |||||
| fed7d334 » | dhh | 2006-03-27 | 1011 | def reset_table_name #:nodoc: | |
| bcbce90b » | jeremy | 2006-08-25 | 1012 | base = base_class | |
| 1013 | |||||
| 1014 | name = | ||||
| 1015 | # STI subclasses always use their superclass' table. | ||||
| 1016 | unless self == base | ||||
| 1017 | base.table_name | ||||
| 1018 | else | ||||
| 1019 | # Nested classes are prefixed with singular parent table name. | ||||
| 1020 | if parent < ActiveRecord::Base && !parent.abstract_class? | ||||
| 1021 | contained = parent.table_name | ||||
| 1022 | contained = contained.singularize if parent.pluralize_table_names | ||||
| 1023 | contained << '_' | ||||
| 1024 | end | ||||
| 1025 | name = "#{table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}" | ||||
| 1026 | end | ||||
| 1027 | |||||
| c450a36f » | dhh | 2006-03-05 | 1028 | set_table_name(name) | |
| d736568f » | Marcel Molina | 2005-10-10 | 1029 | name | |
| db045dbb » | dhh | 2004-11-23 | 1030 | end | |
| 1031 | |||||
| 098fa943 » | dhh | 2005-02-07 | 1032 | # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the | |
| db045dbb » | dhh | 2004-11-23 | 1033 | # primary_key_prefix_type setting, though. | |
| 1034 | def primary_key | ||||
| c0899bca » | Marcel Molina | 2005-10-06 | 1035 | reset_primary_key | |
| 1036 | end | ||||
| 1037 | |||||
| fed7d334 » | dhh | 2006-03-27 | 1038 | def reset_primary_key #:nodoc: | |
| dfa68883 » | jeremy | 2008-03-18 | 1039 | key = get_primary_key(base_class.name) | |
| 1040 | set_primary_key(key) | ||||
| 1041 | key | ||||
| 1042 | end | ||||
| 1043 | |||||
| 1044 | def get_primary_key(base_name) #:nodoc: | ||||
| c0899bca » | Marcel Molina | 2005-10-06 | 1045 | key = 'id' | |
| db045dbb » | dhh | 2004-11-23 | 1046 | case primary_key_prefix_type | |
| 1047 | when :table_name | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 1048 | key = base_name.to_s.foreign_key(false) | |
| db045dbb » | dhh | 2004-11-23 | 1049 | when :table_name_with_underscore | |
| 3b0e1d90 » | josh | 2008-05-14 | 1050 | key = base_name.to_s.foreign_key | |
| db045dbb » | dhh | 2004-11-23 | 1051 | end | |
| c0899bca » | Marcel Molina | 2005-10-06 | 1052 | key | |
| db045dbb » | dhh | 2004-11-23 | 1053 | end | |
| 1054 | |||||
| 9d2da046 » | jeremy | 2006-11-09 | 1055 | # Defines the column name for use with single table inheritance | |
| 1056 | # -- can be set in subclasses like so: self.inheritance_column = "type_id" | ||||
| db045dbb » | dhh | 2004-11-23 | 1057 | def inheritance_column | |
| 9d2da046 » | jeremy | 2006-11-09 | 1058 | @inheritance_column ||= "type".freeze | |
| db045dbb » | dhh | 2004-11-23 | 1059 | end | |
| 1060 | |||||
| 7c8f3edc » | jeremy | 2005-11-12 | 1061 | # Lazy-set the sequence name to the connection's default. This method | |
| 1062 | # is only ever called once since set_sequence_name overrides it. | ||||
| fed7d334 » | dhh | 2006-03-27 | 1063 | def sequence_name #:nodoc: | |
| 7c8f3edc » | jeremy | 2005-11-12 | 1064 | reset_sequence_name | |
| 1065 | end | ||||
| 1066 | |||||
| fed7d334 » | dhh | 2006-03-27 | 1067 | def reset_sequence_name #:nodoc: | |
| 7c8f3edc » | jeremy | 2005-11-12 | 1068 | default = connection.default_sequence_name(table_name, primary_key) | |
| 1069 | set_sequence_name(default) | ||||
| 1070 | default | ||||
| 14ea3128 » | dhh | 2005-07-24 | 1071 | end | |
| 1072 | |||||
| 1aa82b32 » | dhh | 2005-02-07 | 1073 | # Sets the table name to use to the given value, or (if the value | |
| 4eab3758 » | dhh | 2005-02-23 | 1074 | # is nil or false) to the value returned by the given block. | |
| 1aa82b32 » | dhh | 2005-02-07 | 1075 | # | |
| 1076 | # class Project < ActiveRecord::Base | ||||
| 1077 | # set_table_name "project" | ||||
| 1078 | # end | ||||
| c9c18520 » | dhh | 2006-03-27 | 1079 | def set_table_name(value = nil, &block) | |
| 1aa82b32 » | dhh | 2005-02-07 | 1080 | define_attr_method :table_name, value, &block | |
| 1081 | end | ||||
| 1082 | alias :table_name= :set_table_name | ||||
| 1083 | |||||
| 1084 | # Sets the name of the primary key column to use to the given value, | ||||
| 1085 | # or (if the value is nil or false) to the value returned by the given | ||||
| 4eab3758 » | dhh | 2005-02-23 | 1086 | # block. | |
| 1aa82b32 » | dhh | 2005-02-07 | 1087 | # | |
| 1088 | # class Project < ActiveRecord::Base | ||||
| 1089 | # set_primary_key "sysid" | ||||
| 1090 | # end | ||||
| c9c18520 » | dhh | 2006-03-27 | 1091 | def set_primary_key(value = nil, &block) | |
| 1aa82b32 » | dhh | 2005-02-07 | 1092 | define_attr_method :primary_key, value, &block | |
| 1093 | end | ||||
| 1094 | alias :primary_key= :set_primary_key | ||||
| 1095 | |||||
| 1096 | # Sets the name of the inheritance column to use to the given value, | ||||
| 1097 | # or (if the value # is nil or false) to the value returned by the | ||||
| 4eab3758 » | dhh | 2005-02-23 | 1098 | # given block. | |
| 1aa82b32 » | dhh | 2005-02-07 | 1099 | # | |
| 1100 | # class Project < ActiveRecord::Base | ||||
| 1101 | # set_inheritance_column do | ||||
| 1102 | # original_inheritance_column + "_id" | ||||
| 1103 | # end | ||||
| 1104 | # end | ||||
| c9c18520 » | dhh | 2006-03-27 | 1105 | def set_inheritance_column(value = nil, &block) | |
| 1aa82b32 » | dhh | 2005-02-07 | 1106 | define_attr_method :inheritance_column, value, &block | |
| 1107 | end | ||||
| 1108 | alias :inheritance_column= :set_inheritance_column | ||||
| 1109 | |||||
| 14ea3128 » | dhh | 2005-07-24 | 1110 | # Sets the name of the sequence to use when generating ids to the given | |
| 1111 | # value, or (if the value is nil or false) to the value returned by the | ||||
| 7117fdb8 » | jeremy | 2005-10-15 | 1112 | # given block. This is required for Oracle and is useful for any | |
| 1113 | # database which relies on sequences for primary key generation. | ||||
| 14ea3128 » | dhh | 2005-07-24 | 1114 | # | |
| 2076dca6 » | jeremy | 2005-11-16 | 1115 | # If a sequence name is not explicitly set when using Oracle or Firebird, | |
| 1116 | # it will default to the commonly used pattern of: #{table_name}_seq | ||||
| 1117 | # | ||||
| 1118 | # If a sequence name is not explicitly set when using PostgreSQL, it | ||||
| 1119 | # will discover the sequence corresponding to your primary key for you. | ||||
| 14ea3128 » | dhh | 2005-07-24 | 1120 | # | |
| 1121 | # class Project < ActiveRecord::Base | ||||
| 1122 | # set_sequence_name "projectseq" # default would have been "project_seq" | ||||
| 1123 | # end | ||||
| c9c18520 » | dhh | 2006-03-27 | 1124 | def set_sequence_name(value = nil, &block) | |
| 14ea3128 » | dhh | 2005-07-24 | 1125 | define_attr_method :sequence_name, value, &block | |
| 1126 | end | ||||
| 1127 | alias :sequence_name= :set_sequence_name | ||||
| 1128 | |||||
| db045dbb » | dhh | 2004-11-23 | 1129 | # Turns the +table_name+ back into a class name following the reverse rules of +table_name+. | |
| 1130 | def class_name(table_name = table_name) # :nodoc: | ||||
| 1131 | # remove any prefix and/or suffix from the table name | ||||
| 81737fc0 » | jeremy | 2005-07-03 | 1132 | class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize | |
| 1133 | class_name = class_name.singularize if pluralize_table_names | ||||
| 1134 | class_name | ||||
| db045dbb » | dhh | 2004-11-23 | 1135 | end | |
| 1136 | |||||
| 816f37a2 » | dhh | 2005-10-28 | 1137 | # Indicates whether the table associated with this class exists | |
| 1138 | def table_exists? | ||||
| 8877ab58 » | tarmo | 2008-05-06 | 1139 | connection.table_exists?(table_name) | |
| 816f37a2 » | dhh | 2005-10-28 | 1140 | end | |
| 1141 | |||||
| db045dbb » | dhh | 2004-11-23 | 1142 | # Returns an array of column objects for the table associated with this class. | |
| 1143 | def columns | ||||
| 8b5f4e47 » | jeremy | 2007-12-22 | 1144 | unless defined?(@columns) && @columns | |
| c0899bca » | Marcel Molina | 2005-10-06 | 1145 | @columns = connection.columns(table_name, "#{name} Columns") | |
| 8b5f4e47 » | jeremy | 2007-12-22 | 1146 | @columns.each { |column| column.primary = column.name == primary_key } | |
| c0899bca » | Marcel Molina | 2005-10-06 | 1147 | end | |
| 1148 | @columns | ||||
| db045dbb » | dhh | 2004-11-23 | 1149 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 1150 | ||
| 3b4450bb » | NZKoz | 2006-12-27 | 1151 | # Returns a hash of column objects for the table associated with this class. | |
| db045dbb » | dhh | 2004-11-23 | 1152 | def columns_hash | |
| 1153 | @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash } | ||||
| 1154 | end | ||||
| d0bd3b5a » | jeremy | 2005-06-11 | 1155 | ||
| fed7d334 » | dhh | 2006-03-27 | 1156 | # Returns an array of column names as strings. | |
| 49d0f0cb » | dhh | 2005-04-18 | 1157 | def column_names | |
| d0bd3b5a » | jeremy | 2005-06-11 | 1158 | @column_names ||= columns.map { |column| column.name } | |
| 49d0f0cb » | dhh | 2005-04-18 | 1159 | end | |
| db045dbb » | dhh | 2004-11-23 | 1160 | ||
| 2948910b » | Marcel Molina | 2005-10-10 | 1161 | # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", | |
| 1162 | # and columns used for single table inheritance have been removed. | ||||
| db045dbb » | dhh | 2004-11-23 | 1163 | def content_columns | |
| c0899bca » | Marcel Molina | 2005-10-06 | 1164 | @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } | |
| db045dbb » | dhh | 2004-11-23 | 1165 | end | |
| 1166 | |||||
| 1167 | # 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 | ||||
| 1168 | # 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 | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 1169 | # is available. | |
| fed7d334 » | dhh | 2006-03-27 | 1170 | def column_methods_hash #:nodoc: | |
| d0bd3b5a » | jeremy | 2005-06-11 | 1171 | @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr| | |
| 3ab3a70b » | jeremy | 2005-10-22 | 1172 | attr_name = attr.to_s | |
| 1173 | methods[attr.to_sym] = attr_name | ||||
| 1174 | methods["#{attr}=".to_sym] = attr_name | ||||
| 1175 | methods["#{attr}?".to_sym] = attr_name | ||||
| 1176 | methods["#{attr}_before_type_cast".to_sym] = attr_name | ||||
| db045dbb » | dhh | 2004-11-23 | 1177 | methods | |
| 1178 | end | ||||
| 1179 | end | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 1180 | ||
| 2948910b » | Marcel Molina | 2005-10-10 | 1181 | # Resets all the cached information about columns, which will cause them to be reloaded on the next request. | |
| 1314f48d » | dhh | 2004-12-12 | 1182 | def reset_column_information | |
| 5b801b59 » | NZKoz | 2007-08-14 | 1183 | generated_methods.each { |name| undef_method(name) } | |
| 1184 | @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @generated_methods = @inheritance_column = nil | ||||
| 1314f48d » | dhh | 2004-12-12 | 1185 | end | |
| 1186 | |||||
| 4eab3758 » | dhh | 2005-02-23 | 1187 | def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc: | |
| 1314f48d » | dhh | 2004-12-12 | 1188 | subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information } | |
| 1189 | end | ||||
| db045dbb » | dhh | 2004-11-23 | 1190 | ||
| 1191 | # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example: | ||||
| 1192 | # Person.human_attribute_name("first_name") # => "First name" | ||||
| 4eab3758 » | dhh | 2005-02-23 | 1193 | # Deprecated in favor of just calling "first_name".humanize | |
| 1194 | def human_attribute_name(attribute_key_name) #:nodoc: | ||||
| 1f7e72ff » | dhh | 2005-01-17 | 1195 | attribute_key_name.humanize | |
| db045dbb » | dhh | 2004-11-23 | 1196 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 1197 | ||
| 06afb8c7 » | jeremy | 2007-01-22 | 1198 | # True if this isn't a concrete subclass needing a STI type condition. | |
| 1199 | def descends_from_active_record? | ||||
| 1200 | if superclass.abstract_class? | ||||
| 1201 | superclass.descends_from_active_record? | ||||
| 1202 | else | ||||
| 1203 | superclass == Base || !columns_hash.include?(inheritance_column) | ||||
| 1204 | end | ||||
| db045dbb » | dhh | 2004-11-23 | 1205 | end | |
| 1206 | |||||
| b4ec9904 » | NZKoz | 2007-10-02 | 1207 | def finder_needs_type_condition? #:nodoc: | |
| 1208 | # This is like this because benchmarking justifies the strange :false stuff | ||||
| 1209 | :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) | ||||
| 1210 | end | ||||
| 1211 | |||||
| d0360a4d » | jeremy | 2007-05-31 | 1212 | # Returns a string like 'Post id:integer, title:string, body:text' | |
| 52a9e508 » | dhh | 2007-04-21 | 1213 | def inspect | |
| d0360a4d » | jeremy | 2007-05-31 | 1214 | if self == Base | |
| 1215 | super | ||||
| 1216 | elsif abstract_class? | ||||
| 1217 | "#{super}(abstract)" | ||||
| bb94ce92 » | NZKoz | 2007-08-05 | 1218 | elsif table_exists? | |
| d0360a4d » | jeremy | 2007-05-31 | 1219 | attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', ' | |
| 1220 | "#{super}(#{attr_list})" | ||||
| bb94ce92 » | NZKoz | 2007-08-05 | 1221 | else | |
| 1222 | "#{super}(Table doesn't exist)" | ||||
| d0360a4d » | jeremy | 2007-05-31 | 1223 | end | |
| 52a9e508 » | dhh | 2007-04-21 | 1224 | end | |
| 1225 | |||||
| b445ab98 » | NZKoz | 2006-09-04 | 1226 | ||
| 1227 | def quote_value(value, column = nil) #:nodoc: | ||||
| b2c0ddf0 » | Marcel Molina | 2006-04-27 | 1228 | connection.quote(value,column) | |
| 49403831 » | dhh | 2004-12-07 | 1229 | end | |
| 1230 | |||||
| 7143d801 » | Marcel Molina | 2007-11-07 | 1231 | # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. | |
| 4eab3758 » | dhh | 2005-02-23 | 1232 | def sanitize(object) #:nodoc: | |
| 49403831 » | dhh | 2004-12-07 | 1233 | connection.quote(object) | |
| db045dbb » | dhh | 2004-11-23 | 1234 | end | |
| 1235 | |||||
| f2a89d78 » | dhh | 2005-09-06 | 1236 | # Log and benchmark multiple statements in a single block. Example: | |
| db045dbb » | dhh | 2004-11-23 | 1237 | # | |
| 1238 | # Project.benchmark("Creating project") do | ||||
| 1239 | # project = Project.create("name" => "stuff") | ||||
| 1240 | # project.create_manager("name" => "David") | ||||
| 3dfa56cc » | dhh | 2005-06-26 | 1241 | # project.milestones << Milestone.find(:all) | |
| db045dbb » | dhh | 2004-11-23 | 1242 | # end | |
| 5e8e8d65 » | dhh | 2005-09-06 | 1243 | # | |
| 15b38efd » | jeremy | 2007-12-20 | 1244 | # The benchmark is only recorded if the current level of the logger is less than or equal to the <tt>log_level</tt>, | |
| 1245 | # which makes it easy to include benchmarking statements in production software that will remain inexpensive because | ||||
| 1246 | # the benchmark will only be conducted if the log level is low enough. | ||||
| f2a89d78 » | dhh | 2005-09-06 | 1247 | # | |
| 2948910b » | Marcel Molina | 2005-10-10 | 1248 | # The logging of the multiple statements is turned off unless <tt>use_silence</tt> is set to false. | |
| f2a89d78 » | dhh | 2005-09-06 | 1249 | def benchmark(title, log_level = Logger::DEBUG, use_silence = true) | |
| 15b38efd » | jeremy | 2007-12-20 | 1250 | if logger && logger.level <= log_level | |
| 5e8e8d65 » | dhh | 2005-09-06 | 1251 | result = nil | |
| 1252 | seconds = Benchmark.realtime { result = use_silence ? silence { yield } : yield } | ||||
| f2a89d78 » | dhh | 2005-09-06 | 1253 | logger.add(log_level, "#{title} (#{'%.5f' % seconds})") | |
| 5e8e8d65 » | dhh | 2005-09-06 | 1254 | result | |
| 1255 | else | ||||
| 1256 | yield | ||||
| 1257 | end | ||||
| c00bf5f0 » | dhh | 2005-02-16 | 1258 | end | |
| 81737fc0 » | jeremy | 2005-07-03 | 1259 | ||
| c00bf5f0 » | dhh | 2005-02-16 | 1260 | # Silences the logger for the duration of the block. | |
| 1261 | def silence | ||||
| 81737fc0 » | jeremy | 2005-07-03 | 1262 | old_logger_level, logger.level = logger.level, Logger::ERROR if logger | |
| 1263 | yield | ||||
| 1264 | ensure | ||||
| 908e9a17 » | dhh | 2005-04-12 | 1265 | logger.level = old_logger_level if logger | |
| db045dbb » | dhh | 2004-11-23 | 1266 | end | |
| 390e6d24 » | jeremy | 2005-11-06 | 1267 | ||
| 97849deb » | dhh | 2005-01-23 | 1268 | # Overwrite the default class equality method to provide support for association proxies. | |
| 1269 | def ===(object) | ||||
| 1270 | object.is_a?(self) | ||||
| 73673256 » | jeremy | 2007-12-09 | 1271 | end | |
| b840e4ed » | Marcel Molina | 2005-10-12 | 1272 | ||
| d2f47503 » | jamis | 2006-01-20 | 1273 | # Returns the base AR subclass that this class descends from. If A | |
| 1274 | # extends AR::Base, A.base_class will return A. If B descends from A | ||||
| 1275 | # through some arbitrarily deep hierarchy, B.base_class will return A. | ||||
| 1276 | def base_class | ||||
| 1277 | class_of_active_record_descendant(self) | ||||
| 1278 | end | ||||
| 1279 | |||||
| 98dc5827 » | lifo | 2008-05-25 | 1280 | # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). | |
| def74603 » | technoweenie | 2006-03-15 | 1281 | attr_accessor :abstract_class | |
| 1282 | |||||
| 1283 | # Returns whether this class is a base AR class. If A is a base class and | ||||
| 1284 | # B descends from A, then B.base_class will return B. | ||||
| 1285 | def abstract_class? | ||||
| 8b5f4e47 » | jeremy | 2007-12-22 | 1286 | defined?(@abstract_class) && @abstract_class == true | |
| def74603 » | technoweenie | 2006-03-15 | 1287 | end | |
| 1288 | |||||
| 4f39382a » | lifo | 2008-04-06 | 1289 | def respond_to?(method_id, include_private = false) | |
| 1290 | if match = matches_dynamic_finder?(method_id) || matches_dynamic_finder_with_initialize_or_create?(method_id) | ||||
| 1291 | return true if all_attributes_exists?(extract_attribute_names_from_match(match)) | ||||
| 1292 | end | ||||
| 1293 | super | ||||
| 1294 | end | ||||
| 1295 | |||||
| db045dbb » | dhh | 2004-11-23 | 1296 | private | |
| c9c18520 » | dhh | 2006-03-27 | 1297 | def find_initial(options) | |
| 361aaa04 » | Aliaksey Kandratsenka | 2008-01-15 | 1298 | options.update(:limit => 1) | |
| c9c18520 » | dhh | 2006-03-27 | 1299 | find_every(options).first | |
| 1300 | end | ||||
| 2fbe0ae7 » | jeremy | 2006-11-05 | 1301 | ||
| d5a4d5ab » | dhh | 2008-03-12 | 1302 | def find_last(options) | |
| 1303 | order = options[:order] | ||||
| 1304 | |||||
| 1305 | if order | ||||
| 1306 | order = reverse_sql_order(order) | ||||
| 1307 | elsif !scoped?(:find, :order) | ||||
| 1308 | order = "#{table_name}.#{primary_key} DESC" | ||||
| 1309 | end | ||||
| 1310 | |||||
| 1311 | if scoped?(:find, :order) | ||||
| 1312 | scoped_order = reverse_sql_order(scope(:find, :order)) | ||||
| 1313 | scoped_methods.select { |s| s[:find].update(:order => scoped_order) } | ||||
| 1314 | end | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 1315 | ||
| d5a4d5ab » | dhh | 2008-03-12 | 1316 | find_initial(options.merge({ :order => order })) | |
| 1317 | end | ||||
| 1318 | |||||
| 1319 | def reverse_sql_order(order_query) | ||||
| 1320 | reversed_query = order_query.split(/,/).each { |s| | ||||
| 1321 | if s.match(/\s(asc|ASC)$/) | ||||
| 1322 | s.gsub!(/\s(asc|ASC)$/, ' DESC') | ||||
| 1323 | elsif s.match(/\s(desc|DESC)$/) | ||||
| 1324 | s.gsub!(/\s(desc|DESC)$/, ' ASC') | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 1325 | elsif !s.match(/\s(asc|ASC|desc|DESC)$/) | |
| d5a4d5ab » | dhh | 2008-03-12 | 1326 | s.concat(' DESC') | |
| 1327 | end | ||||
| 1328 | }.join(',') | ||||
| 1329 | end | ||||
| 3b0e1d90 » | josh | 2008-05-14 | 1330 | ||
| c9c18520 » | dhh | 2006-03-27 | 1331 | def find_every(options) | |
| 355a8ff2 » | jeremy | 2008-01-18 | 1332 | include_associations = merge_includes(scope(:find, :include), options[:include]) | |
| 1333 | |||||
| 1334 | if include_associations.any? && references_eager_loaded_tables?(options) | ||||
| 1335 | records = find_with_associations(options) | ||||
| 1336 | else | ||||
| 1337 | records = find_by_sql(construct_finder_sql(options)) | ||||
| 1338 | if include_associations.any? | ||||
| 1339 | preload_associations(records, include_associations) | ||||
| 1340 | end | ||||
| 1341 | end | ||||
| c9c18520 » | dhh | 2006-03-27 | 1342 | ||
| 1343 | records.each { |record| record.readonly! } if options[:readonly] | ||||
| 1344 | |||||
| 1345 | records | ||||
| 1346 | end | ||||
| 2fbe0ae7 » | jeremy | 2006-11-05 | 1347 | ||
| c9c18520 » | dhh | 2006-03-27 | 1348 | def find_from_ids(ids, options) | |
| 2fbe0ae7 » | jeremy | 2006-11-05 | 1349 | expects_array = ids.first.kind_of?(Array) | |
| c9c18520 » | dhh | 2006-03-27 | 1350 | return ids.first if expects_array && ids.first.empty? | |
| 2fbe0ae7 » | jeremy | 2006-11-05 | 1351 | ||
| c9c18520 » | dhh | 2006-03-27 | 1352 | ids = ids.flatten.compact.uniq | |
| 1353 | |||||
| 1354 | case ids.size | ||||
| 1355 | when 0 | ||||
| 1356 | raise RecordNotFound, "Couldn't find #{name} without an ID" | ||||
| 1357 | when 1 | ||||
| 1358 | result = find_one(ids.first, options) | ||||
| 1359 | expects_array ? [ result ] : result | ||||
| 1360 | else | ||||
| 1361 | find_some(ids, options) | ||||
| 1362 | end | ||||
| 1363 | end | ||||
| 73673256 » | jeremy | 2007-12-09 | 1364 | ||
| c9c18520 » | dhh | 2006-03-27 | 1365 | def find_one(id, options) | |
| 1366 | conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions] | ||||
| 9b6207c3 » | jeremy | 2007-10-15 | 1367 | options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}" | |
| c9c18520 » | dhh | 2006-03-27 | 1368 | ||
| 230c5a06 » | jeremy | 2006-07-07 | 1369 | # Use find_every(options).first since the primary key condition | |
| 1370 | # already ensures we have a single record. Using find_initial adds | ||||
| 1371 | # a superfluous :limit => 1. | ||||
| 1372 | if result = find_every(options).first | ||||
| c9c18520 » | dhh | 2006-03-27 | 1373 | result | |
| 1374 | else | ||||
| 1375 | raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}" | ||||
| 1376 | end | ||||
| 1377 | end | ||||
| 73673256 » | jeremy | 2007-12-09 | 1378 | ||
| c9c18520 » | dhh | 2006-03-27 | 1379 | def find_some(ids, options) | |
| 1380 | conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions] | ||||
| b445ab98 » | NZKoz | 2006-09-04 | 1381 | ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',') | |
| 9b6207c3 » | jeremy | 2007-10-15 | 1382 | options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}" | |
| c9c18520 » | dhh | 2006-03-27 | 1383 | ||
| 1384 | result = find_every(options) | ||||
| 1385 | |||||
| 8158455d » | jeremy | 2007-05-31 | 1386 | # Determine expected size from limit and offset, not just ids.size. | |
| 109926c5 » | jeremy | 2007-05-25 | 1387 | expected_size = | |
| 1388 | if options[:limit] && ids.size > options[:limit] | ||||
| 1389 | options[:limit] | ||||
| 1390 | else | ||||
| 1391 | ids.size | ||||
| 1392 | end | ||||
| 8158455d » | jeremy | 2007-05-31 | 1393 | ||
| 1394 | # 11 ids with limit 3, offset 9 should give 2 results. | ||||
| 1395 | if options[:offset] && (ids.size - options[:offset] < expected_size) | ||||
| 1396 | expected_size = ids.size - options[:offset] | ||||
| 1397 | end | ||||
| 109926c5 » | jeremy | 2007-05-25 | 1398 | ||
| 1399 | if result.size == expected_size | ||||
| c9c18520 » | dhh | 2006-03-27 | 1400 | result | |
| 1401 | else | ||||
| 109926c5 » | jeremy | 2007-05-25 | 1402 | raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions} (found #{result.size} results, but was looking for #{expected_size})" | |
| c9c18520 » | dhh | 2006-03-27 | 1403 | end | |
| 1404 | end | ||||
| 1405 | |||||
| 4b4dd540 » | jeremy | 2006-08-23 | 1406 | # Finder methods must instantiate through this method to work with the | |
| 1407 | # single-table inheritance model that makes it possible to create | ||||
| 1408 | # objects of different types from the same table. | ||||
| db045dbb » | dhh | 2004-11-23 | 1409 | def instantiate(record) | |
| 4b4dd540 » | jeremy | 2006-08-23 | 1410 | object = | |
| eb2fbf05 » | Marcel Molina | 2005-10-09 | 1411 | if subclass_name = record[inheritance_column] | |
| 4b4dd540 » | jeremy | 2006-08-23 | 1412 | # No type given. | |
| eb2fbf05 » | Marcel Molina | 2005-10-09 | 1413 | if subclass_name.empty? | |
| 1414 | allocate | ||||
| 4b4dd540 » | jeremy | 2006-08-23 | 1415 | ||
| eb2fbf05 » | Marcel Molina | 2005-10-09 | 1416 | else | |
| 4b4dd540 » | jeremy | 2006-08-23 | 1417 | # Ignore type if no column is present since it was probably | |
| 1418 | # pulled in from a sloppy join. | ||||
| 9d2da046 » | jeremy | 2006-11-09 | 1419 | unless columns_hash.include?(inheritance_column) | |
| 4b4dd540 » | jeremy | 2006-08-23 | 1420 | allocate | |
| 1421 | |||||
| 1422 | else | ||||
| 1423 | begin | ||||
| 1424 | compute_type(subclass_name).allocate | ||||
| 1425 | rescue NameError | ||||
| 1426 | raise SubclassNotFound, | ||||
| 1427 | "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " + | ||||
| 1428 | "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + | ||||
| 1429 | "Please rename this column if you didn't intend it to be used for storing the inheritance class " + | ||||
| 1430 | "or overwrite #{self.to_s}.inheritance_column to use another column for that information." | ||||
| 1431 | end | ||||
| eb2fbf05 » | Marcel Molina | 2005-10-09 | 1432 | end | |
| 1433 | end | ||||
| 1434 | else | ||||
| 1435 | allocate | ||||
| 81737fc0 » | jeremy | 2005-07-03 | 1436 | end | |
| 605bc775 » | dhh | 2004-12-14 | 1437 | ||
| db045dbb » | dhh | 2004-11-23 | 1438 | object.instance_variable_set("@attributes", record) | |
| 5b801b59 » | NZKoz | 2007-08-14 | 1439 | object.instance_variable_set("@attributes_cache", Hash.new) | |
| 55efae23 » | jeremy | 2007-08-30 | 1440 | ||
| 1441 | if object.respond_to_without_attributes?(:after_find) | ||||
| 1442 | object.send(:callback, :after_find) | ||||
| 1443 | end | ||||
| 1444 | |||||
| 1445 | if object.respond_to_without_attributes?(:after_initialize) | ||||
| 1446 | object.send(:callback, :after_initialize) | ||||
| 1447 | end | ||||
| 1448 | |||||
| 81737fc0 » | jeremy | 2005-07-03 | 1449 | object | |
| db045dbb » | dhh | 2004-11-23 | 1450 | end | |
| 81737fc0 » | jeremy | 2005-07-03 | 1451 | ||
| c7d6d68f » | jeremy | 2006-02-22 | 1452 | # Nest the type name in the same module as this class. | |
| 1453 | # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo | ||||
| db045dbb » | dhh | 2004-11-23 | 1454 | def type_name_with_module(type_name) | |
| 64003677 » | seckar | 2006-04-06 | 1455 | (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}" | |
| db045dbb » | dhh | 2004-11-23 | 1456 | end | |
| 1457 | |||||
| abc895b8 » | dhh | 2005-04-03 | 1458 | def construct_finder_sql(options) | |
| c9c18520 » | dhh | 2006-03-27 | 1459 | scope = scope(:find) | |
| 9b6207c3 » | jeremy | 2007-10-15 | 1460 | sql = "SELECT #{(scope && scope[:select]) || options[:select] || (options[:joins] && quoted_table_name + '.*') || '*'} " | |
| 1461 | sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " | ||||
| 6abda696 » | dhh | 2005-12-02 | 1462 | ||
| c9c18520 » | dhh | 2006-03-27 | 1463 | add_joins!(sql, options, scope) | |
| 1464 | add_conditions!(sql, options[:conditions], scope) | ||||
| 6abda696 » | dhh | 2005-12-02 | 1465 | ||
| 3566be47 » | dhh | 2007-08-21 | 1466 | add_group!(sql, options[:group], scope) | |
| 57a3e440 » | jamis | 2006-11-07 | 1467 | add_order!(sql, options[:order], scope) | |
| c9c18520 » | dhh | 2006-03-27 | 1468 | add_limit!(sql, options, scope) | |
| 15aa6e05 » | jeremy | 2006-06-19 | 1469 | add_lock!(sql, options, scope) | |
| 6abda696 » | dhh | 2005-12-02 | 1470 | ||
| 6e39c9e5 » | jeremy | 2005-07-03 | 1471 | sql | |
| efb55d1c » | dhh | 2005-04-03 | 1472 | end | |
| abc895b8 » | dhh | 2005-04-03 | 1473 | ||
| 445cb5c0 » | NZKoz | 2006-03-26 | 1474 | # Merges includes so that the result is a valid +include+ | |
| 1475 | def merge_includes(first, second) | ||||
| 01a52dd1 » | dhh | 2006-06-03 | 1476 | (safe_to_array(first) + safe_to_array(second)).uniq | |
| 445cb5c0 » | NZKoz | 2006-03-26 | 1477 | end | |
| 1478 | |||||
| 0ff03199 » | jeremy | 2008-03-22 | 1479 | # Merges conditions so that the result is a valid +condition+ | |
| 1480 | def merge_conditions(*conditions) | ||||
| 1481 | segments = [] | ||||
| 1482 | |||||
| 1483 | conditions.each do |condition| | ||||
| 1484 | unless condition.blank? | ||||
| 1485 | sql = sanitize_sql(condition) | ||||
| 1486 | segments << sql unless sql.blank? | ||||
| 1487 | end | ||||
| 1488 | end | ||||
| 1489 | |||||
| 1490 | "(#{segments.join(') AND (')})" unless segments.empty? | ||||
| 1491 | end | ||||
| 1492 | |||||
| 48052d70 » | jeremy | 2006-06-02 | 1493 | # Object#to_a is deprecated, though it does have the desired behavior | |
| 445cb5c0 » | NZKoz | 2006-03-26 | 1494 | def safe_to_array(o) | |
| 1495 | case o | ||||
| 1496 | when NilClass | ||||
| 1497 | [] | ||||
| 1498 | when Array | ||||
| 1499 | o | ||||
| 1500 | else | ||||
| 1501 | [o] | ||||
| 1502 | end | ||||
| 1503 | end | ||||
| 1504 | |||||
| 57a3e440 » | jamis | 2006-11-07 | 1505 | def add_order!(sql, order, scope = :auto) | |
| 1506 | scope = scope(:find) if :auto == scope | ||||
| 1507 | scoped_order = scope[:order] if scope | ||||
| 91531372 » | Marcel Molina | 2006-04-25 | 1508 | if order | |
| 1509 | sql << " ORDER BY #{order}" | ||||
| 57a3e440 » | jamis | 2006-11-07 | 1510 | sql << ", #{scoped_order}" if scoped_order | |
| 91531372 » | Marcel Molina | 2006-04-25 | 1511 | else | |
| 57a3e440 » | jamis | 2006-11-07 | 1512 | sql << " ORDER BY #{scoped_order}" if scoped_order | |
| 91531372 » | Marcel Molina | 2006-04-25 | 1513 | end | |
| 1514 | end | ||||
| 3566be47 » | dhh | 2007-08-21 | 1515 | ||
| 54a6ed14 » | jeremy | 2007-09-13 | 1516 | def add_group!(sql, group, scope = :auto) | |
| 3566be47 » | dhh | 2007-08-21 | 1517 | if group | |
| 1518 | sql << " GROUP BY #{group}" | ||||
| 54a6ed14 » | jeremy | 2007-09-13 | 1519 | else | |
| 1520 | scope = scope(:find) if :auto == scope | ||||
| 1521 | if scope && (scoped_group = scope[:group]) | ||||
| 1522 | sql << " GROUP BY #{scoped_group}" | ||||
| 1523 | end | ||||
| 1524 | end | ||||
| 3566be47 » | dhh | 2007-08-21 | 1525 | end | |
| 91531372 » | Marcel Molina | 2006-04-25 | 1526 | ||
| 64092de2 » | fxn | 2008-05-02 | 1527 | # The optional scope argument is for the current <tt>:find</tt> scope. | |
| db7fadd7 » | technoweenie | 2006-04-03 | 1528 | def add_limit!(sql, options, scope = :auto) | |
| 1529 | scope = scope(:find) if :auto == scope | ||||
| 54a6ed14 » | jeremy | 2007-09-13 | 1530 | ||
| 1531 | if scope | ||||
| 1532 | options[:limit] ||= scope[:limit] | ||||
| 1533 | options[:offset] ||= scope[:offset] | ||||
| 1534 | end | ||||
| 1535 | |||||
| f2a29ca4 » | dhh | 2005-07-01 | 1536 | connection.add_limit_offset!(sql, options) | |
| abc895b8 » | dhh | 2005-04-03 | 1537 | end | |
| 390e6d24 » | jeremy | 2005-11-06 | 1538 | ||
| 64092de2 » | fxn | 2008-05-02 | 1539 | # The optional scope argument is for the current <tt>:find</tt> scope. | |
| 1540 | # The <tt>:lock</tt> option has precedence over a scoped <tt>:lock</tt>. | ||||
| 15aa6e05 » | jeremy | 2006-06-19 | 1541 | def add_lock!(sql, options, scope = :auto) | |
| c302cdfc » | jeremy | 2007-01-12 | 1542 | scope = scope(:find) if :auto == scope | |
| 15aa6e05 » | jeremy | 2006-06-19 | 1543 | options = options.reverse_merge(:lock => scope[:lock]) if scope | |
| 1544 | connection.add_lock!(sql, options) | ||||
| 1545 | end | ||||
| 1546 | |||||
| 64092de2 » | fxn | 2008-05-02 | 1547 | # The optional scope argument is for the current <tt>:find</tt> scope. | |
| db7fadd7 » | technoweenie | 2006-04-03 | 1548 | def add_joins!(sql, options, scope = :auto) | |
| 1549 | scope = scope(:find) if :auto == scope | ||||
| 2c6e616b » | dhh | 2008-03-13 | 1550 | [(scope && scope[:joins]), options[:joins]].each do |join| | |
| 1551 | case join | ||||
| 1552 | when Symbol, Hash, Array | ||||
| 1553 | join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil) | ||||
| 1554 | sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} " | ||||
| 1555 | else | ||||
| 1556 | sql << " #{join} " | ||||
| 1557 | end | ||||
| 37adea6f » | dhh | 2007-11-07 | 1558 | end | |
| 34f9d30e » | dhh | 2005-07-22 | 1559 | end | |
| 390e6d24 » | jeremy | 2005-11-06 | 1560 | ||
| 2948910b » | Marcel Molina | 2005-10-10 | 1561 | # Adds a sanitized version of +conditions+ to the +sql+ string. Note that the passed-in +sql+ string is changed. | |
| 64092de2 » | fxn | 2008-05-02 | 1562 | # The optional scope argument is for the current <tt>:find</tt> scope. | |
| db7fadd7 » | technoweenie | 2006-04-03 | 1563 | def add_conditions!(sql, conditions, scope = :auto) | |
| 1564 | scope = scope(:find) if :auto == scope | ||||
| 0ff03199 » | jeremy | 2008-03-22 | 1565 | conditions = [conditions] | |
| 1566 | conditions << scope[:conditions] if scope | ||||
| 1567 | conditions << type_condition if finder_needs_type_condition? | ||||
| 1568 | merged_conditions = merge_conditions(*conditions) | ||||
| 1569 | sql << "WHERE #{merged_conditions} " unless merged_conditions.blank? | ||||
| db045dbb » | dhh | 2004-11-23 | 1570 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 1571 | ||
| db045dbb » | dhh | 2004-11-23 | 1572 | def type_condition | |
| 2076dca6 » | jeremy | 2005-11-16 | 1573 | quoted_inheritance_column = connection.quote_column_name(inheritance_column) | |
| bca8751e » | divoxx | 2008-04-11 | 1574 | type_condition = subclasses.inject("#{quoted_table_name}.#{quoted_inheritance_column} = '#{store_full_sti_class ? name : name.demodulize}' ") do |condition, subclass| | |
| 1575 | condition << "OR #{quoted_table_name}.#{quoted_inheritance_column} = '#{store_full_sti_class ? subclass.name : subclass.name.demodulize}' " | ||||
| fdd26813 » | dhh | 2005-04-10 | 1576 | end | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 1577 | ||
| 1578 | " (#{type_condition}) " | ||||
| db045dbb » | dhh | 2004-11-23 | 1579 | end | |
| 1580 | |||||
| 1581 | # Guesses the table name, but does not decorate it with prefix and suffix information. | ||||
| def74603 » | technoweenie | 2006-03-15 | 1582 | def undecorated_table_name(class_name = base_class.name) | |
| 3b0e1d90 » | josh | 2008-05-14 | 1583 | table_name = class_name.to_s.demodulize.underscore | |
| 1584 | table_name = table_name.pluralize if pluralize_table_names | ||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 1585 | table_name | |
| db045dbb » | dhh | 2004-11-23 | 1586 | end | |
| 1587 | |||||
| 6e39c9e5 » | jeremy | 2005-07-03 | 1588 | # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into | |
| 1589 | # find(:first, :conditions => ["user_name = ?", user_name]) and find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password]) | ||||
| 7143d801 » | Marcel Molina | 2007-11-07 | 1590 | # respectively. Also works for find(:all) by using find_all_by_amount(50) that is turned into find(:all, :conditions => ["amount = ?", 50]). | |
| 6e39c9e5 » | jeremy | 2005-07-03 | 1591 | # | |
| 0591c53e » | dhh | 2005-04-17 | 1592 | # It's even possible to use all the additional parameters to find. For example, the full interface for find_all_by_amount | |
| 1593 | # is actually find_all_by_amount(amount, options). | ||||
| 2a305949 » | technoweenie | 2007-03-27 | 1594 | # | |
| 73673256 » | jeremy | 2007-12-09 | 1595 | # This also enables you to initialize a record if it is not found, such as find_or_initialize_by_amount(amount) | |
| 2a305949 » | technoweenie | 2007-03-27 | 1596 | # or find_or_create_by_user_and_password(user, password). | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1597 | # | |
| 1598 | # Each dynamic finder or initializer/creator is also defined in the class after it is first invoked, so that future | ||||
| 1599 | # attempts to use it do not run through method_missing. | ||||
| ac8fd7df » | dhh | 2005-01-02 | 1600 | def method_missing(method_id, *arguments) | |
| 4f39382a » | lifo | 2008-04-06 | 1601 | if match = matches_dynamic_finder?(method_id) | |
| 7858a32e » | jeremy | 2007-06-11 | 1602 | finder = determine_finder(match) | |
| ac8fd7df » | dhh | 2005-01-02 | 1603 | ||
| a5a82d97 » | dhh | 2005-11-04 | 1604 | attribute_names = extract_attribute_names_from_match(match) | |
| 1605 | super unless all_attributes_exists?(attribute_names) | ||||
| 93ec1303 » | dhh | 2005-01-24 | 1606 | ||
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1607 | self.class_eval %{ | |
| 73673256 » | jeremy | 2007-12-09 | 1608 | def self.#{method_id}(*args) | |
| 0c0610d3 » | jeremy | 2007-12-27 | 1609 | options = args.extract_options! | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1610 | attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args) | |
| 1611 | finder_options = { :conditions => attributes } | ||||
| 1612 | validate_find_options(options) | ||||
| c9c18520 » | dhh | 2006-03-27 | 1613 | set_readonly_option!(options) | |
| 1614 | |||||
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1615 | if options[:conditions] | |
| 1616 | with_scope(:find => finder_options) do | ||||
| 1617 | ActiveSupport::Deprecation.silence { send(:#{finder}, options) } | ||||
| c9c18520 » | dhh | 2006-03-27 | 1618 | end | |
| 1619 | else | ||||
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1620 | ActiveSupport::Deprecation.silence { send(:#{finder}, options.merge(finder_options)) } | |
| 297618bd » | Marcel Molina | 2006-01-22 | 1621 | end | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1622 | end | |
| 0ad5365b » | Tobias Lütke | 2007-10-10 | 1623 | }, __FILE__, __LINE__ | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1624 | send(method_id, *arguments) | |
| 4f39382a » | lifo | 2008-04-06 | 1625 | elsif match = matches_dynamic_finder_with_initialize_or_create?(method_id) | |
| d19e4642 » | sstephenson | 2006-06-20 | 1626 | instantiator = determine_instantiator(match) | |
| a5a82d97 » | dhh | 2005-11-04 | 1627 | attribute_names = extract_attribute_names_from_match(match) | |
| 1628 | super unless all_attributes_exists?(attribute_names) | ||||
| 1629 | |||||
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1630 | self.class_eval %{ | |
| 73673256 » | jeremy | 2007-12-09 | 1631 | def self.#{method_id}(*args) | |
| c10b2255 » | dhh | 2008-03-25 | 1632 | guard_protected_attributes = false | |
| 3b0e1d90 » | josh | 2008-05-14 | 1633 | ||
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1634 | if args[0].is_a?(Hash) | |
| c10b2255 » | dhh | 2008-03-25 | 1635 | guard_protected_attributes = true | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1636 | attributes = args[0].with_indifferent_access | |
| 1637 | find_attributes = attributes.slice(*[:#{attribute_names.join(',:')}]) | ||||
| 1638 | else | ||||
| 1639 | find_attributes = attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args) | ||||
| 1640 | end | ||||
| 73673256 » | jeremy | 2007-12-09 | 1641 | ||
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1642 | options = { :conditions => find_attributes } | |
| 1643 | set_readonly_option!(options) | ||||
| 2fbe0ae7 » | jeremy | 2006-11-05 | 1644 | ||
| 0ad5365b » | Tobias Lütke | 2007-10-10 | 1645 | record = find_initial(options) | |
| 3b0e1d90 » | josh | 2008-05-14 | 1646 | ||
| c10b2255 » | dhh | 2008-03-25 | 1647 | if record.nil? | |
| 1648 | record = self.new { |r| r.send(:attributes=, attributes, guard_protected_attributes) } | ||||
| 1649 | #{'yield(record) if block_given?'} | ||||
| 0ad5365b » | Tobias Lütke | 2007-10-10 | 1650 | #{'record.save' if instantiator == :create} | |
| 1651 | record | ||||
| 1652 | else | ||||
| 73673256 » | jeremy | 2007-12-09 | 1653 | record | |
| 0ad5365b » | Tobias Lütke | 2007-10-10 | 1654 | end | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1655 | end | |
| 0ad5365b » | Tobias Lütke | 2007-10-10 | 1656 | }, __FILE__, __LINE__ | |
| 4a1388ad » | Tobias Lütke | 2007-09-18 | 1657 | send(method_id, *arguments) | |
| ac8fd7df » | dhh | 2005-01-02 | 1658 | else | |
| 1659 | super | ||||
| 1660 | end | ||||
| 1661 | end | ||||
| db045dbb » | dhh | 2004-11-23 | 1662 | ||
| 4f39382a » | lifo | 2008-04-06 | 1663 | def matches_dynamic_finder?(method_id) | |
| 1664 | /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s) | ||||
| 1665 | end | ||||
| 1666 | |||||
| 1667 | def matches_dynamic_finder_with_initialize_or_create?(method_id) | ||||
| 1668 | /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s) | ||||
| 1669 | end | ||||
| 1670 | |||||
| a5a82d97 » | dhh | 2005-11-04 | 1671 | def determine_finder(match) | |
| c9c18520 » | dhh | 2006-03-27 | 1672 | match.captures.first == 'all_by' ? :find_every : :find_initial | |
| 1673 | end | ||||
| 1674 | |||||
| d19e4642 » | sstephenson | 2006-06-20 | 1675 | def determine_instantiator(match) | |
| 1676 | match.captures.first == 'initialize' ? :new : :create | ||||
| 1677 | end | ||||
| 1678 | |||||
| a5a82d97 » | dhh | 2005-11-04 | 1679 | def extract_attribute_names_from_match(match) | |
| 1680 | match.captures.last.split('_and_') | ||||
| 1681 | end | ||||
| 1682 | |||||
| 1683 | def construct_attributes_from_arguments(attribute_names, arguments) | ||||
| 1684 | attributes = {} | ||||
| 1685 | attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] } | ||||
| 1686 | attributes | ||||
| 1687 | end | ||||
| 1688 | |||||
| abdf546a » | jeremy | 2008-01-18 | 1689 | # Similar in purpose to +expand_hash_conditions_for_aggregates+. | |
| 1690 | def expand_attribute_names_for_aggregates(attribute_names) | ||||
| 1691 | expanded_attribute_names = [] | ||||
| 1692 | attribute_names.each do |attribute_name| | ||||
| 1693 | unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? | ||||
| 1694 | aggregate_mapping(aggregation).each do |field_attr, aggregate_attr| | ||||
| 1695 | expanded_attribute_names << field_attr | ||||
| 1696 | end | ||||
| 1697 | else | ||||
| 1698 | expanded_attribute_names << attribute_name | ||||
| 1699 | end | ||||
| 1700 | end | ||||
| 1701 | expanded_attribute_names | ||||
| 1702 | |||||








