root/trunk/activerecord/lib/active_record/base.rb
| Revision 9235, 115.1 kB (checked in by pratik, 1 year ago) | |
|---|---|
| |
| Line | |
|---|---|
| 1 | require 'yaml' |
| 2 | require 'set' |
| 3 | |
| 4 | module ActiveRecord #:nodoc: |
| 5 | # Generic ActiveRecord exception class. |
| 6 | class ActiveRecordError < StandardError |
| 7 | end |
| 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). |
| 11 | class SubclassNotFound < ActiveRecordError #:nodoc: |
| 12 | end |
| 13 | |
| 14 | # Raised when object assigned to association is of incorrect type. |
| 15 | # |
| 16 | # Example: |
| 17 | # |
| 18 | # class Ticket < ActiveRecord::Base |
| 19 | # has_many :patches |
| 20 | # end |
| 21 | # |
| 22 | # class Patch < ActiveRecord::Base |
| 23 | # belongs_to :ticket |
| 24 | # end |
| 25 | # |
| 26 | # and somewhere in the code: |
| 27 | # |
| 28 | # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.") |
| 29 | # @ticket.save |
| 30 | class AssociationTypeMismatch < ActiveRecordError |
| 31 | end |
| 32 | |
| 33 | # Raised when unserialized object's type mismatches one specified for serializable field. |
| 34 | class SerializationTypeMismatch < ActiveRecordError |
| 35 | end |
| 36 | |
| 37 | # Raised when adapter not specified on connection (or configuration file config/database.yml misses adapter field). |
| 38 | class AdapterNotSpecified < ActiveRecordError |
| 39 | end |
| 40 | |
| 41 | # Raised when ActiveRecord cannot find database adapter specified in config/database.yml or programmatically. |
| 42 | class AdapterNotFound < ActiveRecordError |
| 43 | end |
| 44 | |
| 45 | # Raised when connection to the database could not been established (for example when connection= is given a nil object). |
| 46 | class ConnectionNotEstablished < ActiveRecordError |
| 47 | end |
| 48 | |
| 49 | # Raised when ActiveRecord cannot find record by given id or set of ids. |
| 50 | class RecordNotFound < ActiveRecordError |
| 51 | end |
| 52 | |
| 53 | # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be |
| 54 | # saved because record is invalid. |
| 55 | class RecordNotSaved < ActiveRecordError |
| 56 | end |
| 57 | |
| 58 | # 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). |
| 59 | class StatementInvalid < ActiveRecordError |
| 60 | end |
| 61 | |
| 62 | # Raised when number of bind variables in statement given to :condition key (for example, when using +find+ method) |
| 63 | # does not match number of expected variables. |
| 64 | # |
| 65 | # Example: |
| 66 | # |
| 67 | # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362] |
| 68 | # |
| 69 | # in example above two placeholders are given but only one variable to fill them. |
| 70 | class PreparedStatementInvalid < ActiveRecordError |
| 71 | end |
| 72 | |
| 73 | # Raised on attempt to save stale record. Record is stale when it's being saved in another query after |
| 74 | # instantiation, for example, when two users edit the same wiki page and one starts editing and saves |
| 75 | # the page before the other. |
| 76 | # |
| 77 | # Read more about optimistic locking in +ActiveRecord::Locking+ module RDoc. |
| 78 | class StaleObjectError < ActiveRecordError |
| 79 | end |
| 80 | |
| 81 | # Raised when association is being configured improperly or |
| 82 | # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations. |
| 83 | class ConfigurationError < ActiveRecordError |
| 84 | end |
| 85 | |
| 86 | # Raised on attempt to update record that is instantiated as read only. |
| 87 | class ReadOnlyRecord < ActiveRecordError |
| 88 | end |
| 89 | |
| 90 | # Used by ActiveRecord transaction mechanism to distinguish rollback from other exceptional situations. |
| 91 | # You can use it to roll your transaction back explicitly in the block passed to +transaction+ method. |
| 92 | class Rollback < ActiveRecordError |
| 93 | end |
| 94 | |
| 95 | # Raised when attribute has a name reserved by ActiveRecord (when attribute has name of one of ActiveRecord instance methods). |
| 96 | class DangerousAttributeError < ActiveRecordError |
| 97 | end |
| 98 | |
| 99 | # Raised when you've tried to access a column which wasn't |
| 100 | # loaded by your finder. Typically this is because :select |
| 101 | # has been specified |
| 102 | class MissingAttributeError < NoMethodError |
| 103 | end |
| 104 | |
| 105 | class AttributeAssignmentError < ActiveRecordError #:nodoc: |
| 106 | attr_reader :exception, :attribute |
| 107 | def initialize(message, exception, attribute) |
| 108 | @exception = exception |
| 109 | @attribute = attribute |
| 110 | @message = message |
| 111 | end |
| 112 | end |
| 113 | |
| 114 | class MultiparameterAssignmentErrors < ActiveRecordError #:nodoc: |
| 115 | attr_reader :errors |
| 116 | def initialize(errors) |
| 117 | @errors = errors |
| 118 | end |
| 119 | end |
| 120 | |
| 121 | # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with |
| 122 | # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change |
| 123 | # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain |
| 124 | # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones. |
| 125 | # |
| 126 | # See the mapping rules in table_name and the full example in link:files/README.html for more insight. |
| 127 | # |
| 128 | # == Creation |
| 129 | # |
| 130 | # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when |
| 131 | # you're receiving the data from somewhere else, like an HTTP request. It works like this: |
| 132 | # |
| 133 | # user = User.new(:name => "David", :occupation => "Code Artist") |
| 134 | # user.name # => "David" |
| 135 | # |
| 136 | # You can also use block initialization: |
| 137 | # |
| 138 | # user = User.new do |u| |
| 139 | # u.name = "David" |
| 140 | # u.occupation = "Code Artist" |
| 141 | # end |
| 142 | # |
| 143 | # And of course you can just create a bare object and specify the attributes after the fact: |
| 144 | # |
| 145 | # user = User.new |
| 146 | # user.name = "David" |
| 147 | # user.occupation = "Code Artist" |
| 148 | # |
| 149 | # == Conditions |
| 150 | # |
| 151 | # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement. |
| 152 | # The array form is to be used when the condition input is tainted and requires sanitization. The string form can |
| 153 | # be used for statements that don't involve tainted data. The hash form works much like the array form, except |
| 154 | # only equality and range is possible. Examples: |
| 155 | # |
| 156 | # class User < ActiveRecord::Base |
| 157 | # def self.authenticate_unsafely(user_name, password) |
| 158 | # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'") |
| 159 | # end |
| 160 | # |
| 161 | # def self.authenticate_safely(user_name, password) |
| 162 | # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ]) |
| 163 | # end |
| 164 | # |
| 165 | # def self.authenticate_safely_simply(user_name, password) |
| 166 | # find(:first, :conditions => { :user_name => user_name, :password => password }) |
| 167 | # end |
| 168 | # end |
| 169 | # |
| 170 | # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection |
| 171 | # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and |
| 172 | # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, |
| 173 | # which will ensure that an attacker can't escape the query and fake the login (or worse). |
| 174 | # |
| 175 | # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth |
| 176 | # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing |
| 177 | # the question marks with symbols and supplying a hash with values for the matching symbol keys: |
| 178 | # |
| 179 | # Company.find(:first, :conditions => [ |
| 180 | # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date", |
| 181 | # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' } |
| 182 | # ]) |
| 183 | # |
| 184 | # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND |
| 185 | # operator. For instance: |
| 186 | # |
| 187 | # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 }) |
| 188 | # Student.find(:all, :conditions => params[:student]) |
| 189 | # |
| 190 | # A range may be used in the hash to use the SQL BETWEEN operator: |
| 191 | # |
| 192 | # Student.find(:all, :conditions => { :grade => 9..12 }) |
| 193 | # |
| 194 | # An array may be used in the hash to use the SQL IN operator: |
| 195 | # |
| 196 | # Student.find(:all, :conditions => { :grade => [9,11,12] }) |
| 197 | # |
| 198 | # == Overwriting default accessors |
| 199 | # |
| 200 | # All column values are automatically available through basic accessors on the Active Record object, but sometimes you |
| 201 | # want to specialize this behavior. This can be done by overwriting the default accessors (using the same |
| 202 | # name as the attribute) and calling read_attribute(attr_name) and write_attribute(attr_name, value) to actually change things. |
| 203 | # Example: |
| 204 | # |
| 205 | # class Song < ActiveRecord::Base |
| 206 | # # Uses an integer of seconds to hold the length of the song |
| 207 | # |
| 208 | # def length=(minutes) |
| 209 | # write_attribute(:length, minutes * 60) |
| 210 | # end |
| 211 | # |
| 212 | # def length |
| 213 | # read_attribute(:length) / 60 |
| 214 | # end |
| 215 | # end |
| 216 | # |
| 217 | # You can alternatively use self[:attribute]=(value) and self[:attribute] instead of write_attribute(:attribute, value) and |
| 218 | # read_attribute(:attribute) as a shorter form. |
| 219 | # |
| 220 | # == Attribute query methods |
| 221 | # |
| 222 | # In addition to the basic accessors, query methods are also automatically available on the Active Record object. |
| 223 | # Query methods allow you to test whether an attribute value is present. |
| 224 | # |
| 225 | # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call |
| 226 | # to determine whether the user has a name: |
| 227 | # |
| 228 | # user = User.new(:name => "David") |
| 229 | # user.name? # => true |
| 230 | # |
| 231 | # anonymous = User.new(:name => "") |
| 232 | # anonymous.name? # => false |
| 233 | # |
| 234 | # == Accessing attributes before they have been typecasted |
| 235 | # |
| 236 | # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. |
| 237 | # That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model |
| 238 | # has a balance attribute, you can call account.balance_before_type_cast or account.id_before_type_cast. |
| 239 | # |
| 240 | # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display |
| 241 | # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you |
| 242 | # want. |
| 243 | # |
| 244 | # == Dynamic attribute-based finders |
| 245 | # |
| 246 | # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by |
| 247 | # appending the name of an attribute to <tt>find_by_</tt> or <tt>find_all_by_</tt>, so you get finders like Person.find_by_user_name, |
| 248 | # Person.find_all_by_last_name, Payment.find_by_transaction_id. So instead of writing |
| 249 | # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>. |
| 250 | # 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>. |
| 251 | # |
| 252 | # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like |
| 253 | # <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 |
| 254 | # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do |
| 255 | # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>. |
| 256 | # |
| 257 | # It's even possible to use all the additional parameters to find. For example, the full interface for Payment.find_all_by_amount |
| 258 | # is actually Payment.find_all_by_amount(amount, options). And the full interface to Person.find_by_user_name is |
| 259 | # actually Person.find_by_user_name(user_name, options). So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>. |
| 260 | # |
| 261 | # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with |
| 262 | # <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: |
| 263 | # |
| 264 | # # No 'Summer' tag exists |
| 265 | # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer") |
| 266 | # |
| 267 | # # Now the 'Summer' tag does exist |
| 268 | # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer") |
| 269 | # |
| 270 | # # Now 'Bob' exist and is an 'admin' |
| 271 | # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true } |
| 272 | # |
| 273 | # 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: |
| 274 | # |
| 275 | # # No 'Winter' tag exists |
| 276 | # winter = Tag.find_or_initialize_by_name("Winter") |
| 277 | # winter.new_record? # true |
| 278 | # |
| 279 | # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of |
| 280 | # a list of parameters. For example: |
| 281 | # |
| 282 | # Tag.find_or_create_by_name(:name => "rails", :creator => current_user) |
| 283 | # |
| 284 | # That will either find an existing tag named "rails", or create a new one while setting the user that created it. |
| 285 | # |
| 286 | # == Saving arrays, hashes, and other non-mappable objects in text columns |
| 287 | # |
| 288 | # 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+. |
| 289 | # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example: |
| 290 | # |
| 291 | # class User < ActiveRecord::Base |
| 292 | # serialize :preferences |
| 293 | # end |
| 294 | # |
| 295 | # user = User.create(:preferences => { "background" => "black", "display" => large }) |
| 296 | # User.find(user.id).preferences # => { "background" => "black", "display" => large } |
| 297 | # |
| 298 | # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a |
| 299 | # descendent of a class not in the hierarchy. Example: |
| 300 | # |
| 301 | # class User < ActiveRecord::Base |
| 302 | # serialize :preferences, Hash |
| 303 | # end |
| 304 | # |
| 305 | # user = User.create(:preferences => %w( one two three )) |
| 306 | # User.find(user.id).preferences # raises SerializationTypeMismatch |
| 307 | # |
| 308 | # == Single table inheritance |
| 309 | # |
| 310 | # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed |
| 311 | # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this: |
| 312 | # |
| 313 | # class Company < ActiveRecord::Base; end |
| 314 | # class Firm < Company; end |
| 315 | # class Client < Company; end |
| 316 | # class PriorityClient < Client; end |
| 317 | # |
| 318 | # When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = "Firm". You can then |
| 319 | # fetch this row again using Company.find(:first, "name = '37signals'") and it will return a Firm object. |
| 320 | # |
| 321 | # 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 |
| 322 | # like normal subclasses with no special magic for differentiating between them or reloading the right type with find. |
| 323 | # |
| 324 | # Note, all the attributes for all the cases are kept in the same table. Read more: |
| 325 | # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html |
| 326 | # |
| 327 | # == Connection to multiple databases in different models |
| 328 | # |
| 329 | # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. |
| 330 | # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. |
| 331 | # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection |
| 332 | # and Course *and all its subclasses* will use this connection instead. |
| 333 | # |
| 334 | # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is |
| 335 | # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool. |
| 336 | # |
| 337 | # == Exceptions |
| 338 | # |
| 339 | # * +ActiveRecordError+ -- generic error class and superclass of all other errors raised by Active Record |
| 340 | # * +AdapterNotSpecified+ -- the configuration hash used in <tt>establish_connection</tt> didn't include an |
| 341 | # <tt>:adapter</tt> key. |
| 342 | # * +AdapterNotFound+ -- the <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter |
| 343 | # (or a bad spelling of an existing one). |
| 344 | # * +AssociationTypeMismatch+ -- the object assigned to the association wasn't of the type specified in the association definition. |
| 345 | # * +SerializationTypeMismatch+ -- the serialized object wasn't of the class specified as the second parameter. |
| 346 | # * +ConnectionNotEstablished+ -- no connection has been established. Use <tt>establish_connection</tt> before querying. |
| 347 | # * +RecordNotFound+ -- no record responded to the find* method. |
| 348 | # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions. |
| 349 | # * +StatementInvalid+ -- the database server rejected the SQL statement. The precise error is added in the message. |
| 350 | # Either the record with the given ID doesn't exist or the record didn't meet the additional restrictions. |
| 351 | # * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the |
| 352 | # +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+ |
| 353 | # objects that should be inspected to determine which attributes triggered the errors. |
| 354 | # * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method. |
| 355 | # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error. |
| 356 | # |
| 357 | # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level). |
| 358 | # So it's possible to assign a logger to the class through Base.logger= which will then be used by all |
| 359 | # instances in the current object space. |
| 360 | class Base |
| 361 | # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed |
| 362 | # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+. |
| 363 | cattr_accessor :logger, :instance_writer => false |
| 364 | |
| 365 | def self.inherited(child) #:nodoc: |
| 366 | @@subclasses[self] ||= [] |
| 367 | @@subclasses[self] << child |
| 368 | super |
| 369 | end |
| 370 | |
| 371 | def self.reset_subclasses #:nodoc: |
| 372 | nonreloadables = [] |
| 373 | subclasses.each do |klass| |
| 374 | unless Dependencies.autoloaded? klass |
| 375 | nonreloadables << klass |
| 376 | next |
| 377 | end |
| 378 | klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) } |
| 379 | klass.instance_methods(false).each { |m| klass.send :undef_method, m } |
| 380 | end |
| 381 | @@subclasses = {} |
| 382 | nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass } |
| 383 | end |
| 384 | |
| 385 | @@subclasses = {} |
| 386 | |
| 387 | cattr_accessor :configurations, :instance_writer => false |
| 388 | @@configurations = {} |
| 389 | |
| 390 | # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and |
| 391 | # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as |
| 392 | # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember |
| 393 | # that this is a global setting for all Active Records. |
| 394 | cattr_accessor :primary_key_prefix_type, :instance_writer => false |
| 395 | @@primary_key_prefix_type = nil |
| 396 | |
| 397 | # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all |
| 398 | # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace |
| 399 | # for tables in a shared database. By default, the prefix is the empty string. |
| 400 | cattr_accessor :table_name_prefix, :instance_writer => false |
| 401 | @@table_name_prefix = "" |
| 402 | |
| 403 | # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", |
| 404 | # "people_basecamp"). By default, the suffix is the empty string. |
| 405 | cattr_accessor :table_name_suffix, :instance_writer => false |
| 406 | @@table_name_suffix = "" |
| 407 | |
| 408 | # Indicates whether table names should be the pluralized versions of the corresponding class names. |
| 409 | # If true, the default table name for a +Product+ class will be +products+. If false, it would just be +product+. |
| 410 | # See table_name for the full rules on table/class naming. This is true, by default. |
| 411 | cattr_accessor :pluralize_table_names, :instance_writer => false |
| 412 | @@pluralize_table_names = true |
| 413 | |
| 414 | # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors |
| 415 | # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but |
| 416 | # may complicate matters if you use software like syslog. This is true, by default. |
| 417 | cattr_accessor :colorize_logging, :instance_writer => false |
| 418 | @@colorize_logging = true |
| 419 | |
| 420 | # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database. |
| 421 | # This is set to :local by default. |
| 422 | cattr_accessor :default_timezone, :instance_writer => false |
| 423 | @@default_timezone = :local |
| 424 | |
| 425 | # Determines whether to use a connection for each thread, or a single shared connection for all threads. |
| 426 | # Defaults to false. Set to true if you're writing a threaded application. |
| 427 | cattr_accessor :allow_concurrency, :instance_writer => false |
| 428 | @@allow_concurrency = false |
| 429 | |
| 430 | # Specifies the format to use when dumping the database schema with Rails' |
| 431 | # Rakefile. If :sql, the schema is dumped as (potentially database- |
| 432 | # specific) SQL statements. If :ruby, the schema is dumped as an |
| 433 | # ActiveRecord::Schema file which can be loaded into any database that |
| 434 | # supports migrations. Use :ruby if you want to have different database |
| 435 | # adapters for, e.g., your development and test environments. |
| 436 | cattr_accessor :schema_format , :instance_writer => false |
| 437 | @@schema_format = :ruby |
| 438 | |
| 439 | class << self # Class methods |
| 440 | # Find operates with four different retrieval approaches: |
| 441 | # |
| 442 | # * 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]). |
| 443 | # If no record can be found for all of the listed ids, then RecordNotFound will be raised. |
| 444 | # * Find first: This will return the first record matched by the options used. These options can either be specific |
| 445 | # conditions or merely an order. If no record can be matched, nil is returned. |
| 446 | # * Find last: This will return the last record matched by the options used. These options can either be specific |
| 447 | # conditions or merely an order. If no record can be matched, nil is returned. |
| 448 | # * Find all: This will return all the records matched by the options used. If no records are found, an empty array is returned. |
| 449 | # |
| 450 | # All approaches accept an options hash as their last parameter. The options are: |
| 451 | # |
| 452 | # * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro. |
| 453 | # * <tt>:order</tt>: An SQL fragment like "created_at DESC, name". |
| 454 | # * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. |
| 455 | # * <tt>:limit</tt>: An integer determining the limit on the number of rows that should be returned. |
| 456 | # * <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. |
| 457 | # * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) |
| 458 | # or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s). |
| 459 | # 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. |
| 460 | # Pass :readonly => false to override. |
| 461 | # * <tt>:include</tt>: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer |
| 462 | # to already defined associations. See eager loading under Associations. |
| 463 | # * <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 |
| 464 | # include the joined columns. |
| 465 | # * <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 |
| 466 | # of a database view). |
| 467 | # * <tt>:readonly</tt>: Mark the returned records read-only so they cannot be saved or updated. |
| 468 | # * <tt>:lock</tt>: An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE". |
| 469 | # :lock => true gives connection's default exclusive lock, usually "FOR UPDATE". |
| 470 | # |
| 471 | # Examples for find by id: |
| 472 | # Person.find(1) # returns the object for ID = 1 |
| 473 | # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6) |
| 474 | # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17) |
| 475 | # Person.find([1]) # returns an array for the object with ID = 1 |
| 476 | # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC") |
| 477 | # |
| 478 | # Note that returned records may not be in the same order as the ids you |
| 479 | # provide since database rows are unordered. Give an explicit :order |
| 480 | # to ensure the results are sorted. |
| 481 | # |
| 482 | # Examples for find first: |
| 483 | # Person.find(:first) # returns the first object fetched by SELECT * FROM people |
| 484 | # Person.find(:first, :conditions => [ "user_name = ?", user_name]) |
| 485 | # Person.find(:first, :order => "created_on DESC", :offset => 5) |
| 486 | # |
| 487 | # Examples for find last: |
| 488 | # Person.find(:last) # returns the last object fetched by SELECT * FROM people |
| 489 | # Person.find(:last, :conditions => [ "user_name = ?", user_name]) |
| 490 | # Person.find(:last, :order => "created_on DESC", :offset => 5) |
| 491 | # |
| 492 | # Examples for find all: |
| 493 | # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people |
| 494 | # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) |
| 495 | # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] } |
| 496 | # Person.find(:all, :offset => 10, :limit => 10) |
| 497 | # Person.find(:all, :include => [ :account, :friends ]) |
| 498 | # Person.find(:all, :group => "category") |
| 499 | # |
| 500 | # Example for find with a lock. Imagine two concurrent transactions: |
| 501 | # each will read person.visits == 2, add 1 to it, and save, resulting |
| 502 | # in two saves of person.visits = 3. By locking the row, the second |
| 503 | # transaction has to wait until the first is finished; we get the |
| 504 | # expected person.visits == 4. |
| 505 | # Person.transaction do |
| 506 | # person = Person.find(1, :lock => true) |
| 507 | # person.visits += 1 |
| 508 | # person.save! |
| 509 | # end |
| 510 | def find(*args) |
| 511 | options = args.extract_options! |
| 512 | validate_find_options(options) |
| 513 | set_readonly_option!(options) |
| 514 | |
| 515 | case args.first |
| 516 | when :first then find_initial(options) |
| 517 | when :last then find_last(options) |
| 518 | when :all then find_every(options) |
| 519 | else find_from_ids(args, options) |
| 520 | end |
| 521 | end |
| 522 | |
| 523 | # This is an alias for find(:first). You can pass in all the same arguments to this method as you can |
| 524 | # to find(:first) |
| 525 | def first(*args) |
| 526 | find(:first, *args) |
| 527 | end |
| 528 | |
| 529 | # This is an alias for find(:last). You can pass in all the same arguments to this method as you can |
| 530 | # to find(:last) |
| 531 | def last(*args) |
| 532 | find(:last, *args) |
| 533 | end |
| 534 | |
| 535 | # |
| 536 | # Executes a custom sql query against your database and returns all the results. The results will |
| 537 | # be returned as an array with columns requested encapsulated as attributes of the model you call |
| 538 | # this method from. If you call +Product.find_by_sql+ then the results will be returned in a Product |
| 539 | # object with the attributes you specified in the SQL query. |
| 540 | # |
| 541 | # If you call a complicated SQL query which spans multiple tables the columns specified by the |
| 542 | # SELECT will be attributes of the model, whether or not they are columns of the corresponding |
| 543 | # table. |
| 544 | # |
| 545 | # The +sql+ parameter is a full sql query as a string. It will be called as is, there will be |
| 546 | # no database agnostic conversions performed. This should be a last resort because using, for example, |
| 547 | # MySQL specific terms will lock you to using that particular database engine or require you to |
| 548 | # change your call if you switch engines |
| 549 | # |
| 550 | # ==== Examples |
| 551 | # # A simple sql query spanning multiple tables |
| 552 | # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" |
| 553 | # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...] |
| 554 | # |
| 555 | # # You can use the same string replacement techniques as you can with ActiveRecord#find |
| 556 | # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] |
| 557 | # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...] |
| 558 | def find_by_sql(sql) |
| 559 | connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) } |
| 560 | end |
| 561 | |
| 562 | # Checks whether a record exists in the database that matches conditions given. These conditions |
| 563 | # can either be a single integer representing a primary key id to be found, or a condition to be |
| 564 | # matched like using ActiveRecord#find. |
| 565 | # |
| 566 | # The +id_or_conditions+ parameter can be an Integer or a String if you want to search the primary key |
| 567 | # column of the table for a matching id, or if you're looking to match against a condition you can use |
| 568 | # an Array or a Hash. |
| 569 | # |
| 570 | # Possible gotcha: You can't pass in a condition as a string e.g. "name = 'Jamie'", this would be |
| 571 | # sanitized and then queried against the primary key column as "id = 'name = \'Jamie" |
| 572 | # |
| 573 | # ==== Examples |
| 574 | # Person.exists?(5) |
| 575 | # Person.exists?('5') |
| 576 | # Person.exists?(:name => "David") |
| 577 | # Person.exists?(['name LIKE ?', "%#{query}%"]) |
| 578 | def exists?(id_or_conditions) |
| 579 | connection.select_all( |
| 580 | construct_finder_sql( |
| 581 | :select => "#{quoted_table_name}.#{primary_key}", |
| 582 | :conditions => expand_id_conditions(id_or_conditions), |
| 583 | :limit => 1 |
| 584 | ), |
| 585 | "#{name} Exists" |
| 586 | ).size > 0 |
| 587 | end |
| 588 | |
| 589 | # Creates an object (or multiple objects) and saves it to the database, if validations pass. |
| 590 | # The resulting object is returned whether the object was saved successfully to the database or not. |
| 591 | # |
| 592 | # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the |
| 593 | # attributes on the objects that are to be created. |
| 594 | # |
| 595 | # ==== Examples |
| 596 | # # Create a single new object |
| 597 | # User.create(:first_name => 'Jamie') |
| 598 | # # Create an Array of new objects |
| 599 | # User.create([{:first_name => 'Jamie'}, {:first_name => 'Jeremy'}]) |
| 600 | def create(attributes = nil) |
| 601 | if attributes.is_a?(Array) |
| 602 | attributes.collect { |attr| create(attr) } |
| 603 | else |
| 604 | object = new(attributes) |
| 605 | object.save |
| 606 | object |
| 607 | end |
| 608 | end |
| 609 | |
| 610 | # Updates an object (or multiple objects) and saves it to the database, if validations pass. |
| 611 | # The resulting object is returned whether the object was saved successfully to the database or not. |
| 612 | # |
| 613 | # ==== Options |
| 614 | # |
| 615 | # +id+ This should be the id or an array of ids to be updated |
| 616 | # +attributes+ This should be a Hash of attributes to be set on the object, or an array of Hashes. |
| 617 | # |
| 618 | # ==== Examples |
| 619 | # |
| 620 | # # Updating one record: |
| 621 | # Person.update(15, {:user_name => 'Samuel', :group => 'expert'}) |
| 622 | # |
| 623 | # # Updating multiple records: |
| 624 | # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} } |
| 625 | # Person.update(people.keys, people.values) |
| 626 | def update(id, attributes) |
| 627 | if id.is_a?(Array) |
| 628 | idx = -1 |
| 629 | id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) } |
| 630 | else |
| 631 | object = find(id) |
| 632 | object.update_attributes(attributes) |
| 633 | object |
| 634 | end |
| 635 | end |
| 636 | |
| 637 | # Delete an object (or multiple objects) where the +id+ given matches the primary_key. A SQL +DELETE+ command |
| 638 | # is executed on the database which means that no callbacks are fired off running this. This is an efficient method |
| 639 | # of deleting records that don't need cleaning up after or other actions to be taken. |
| 640 | # |
| 641 | # Objects are _not_ instantiated with this method. |
| 642 | # |
| 643 | # ==== Options |
| 644 | # |
| 645 | # +id+ Can be either an Integer or an Array of Integers |
| 646 | # |
| 647 | # ==== Examples |
| 648 | # |
| 649 | # # Delete a single object |
| 650 | # Todo.delete(1) |
| 651 | # |
| 652 | # # Delete multiple objects |
| 653 | # todos = [1,2,3] |
| 654 | # Todo.delete(todos) |
| 655 | def delete(id) |
| 656 | delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ]) |
| 657 | end |
| 658 | |
| 659 | # Destroy an object (or multiple objects) that has the given id, the object is instantiated first, |
| 660 | # therefore all callbacks and filters are fired off before the object is deleted. This method is |
| 661 | # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run. |
| 662 | # |
| 663 | # This essentially finds the object (or multiple objects) with the given id, creates a new object |
| 664 | # from the attributes, and then calls destroy on it. |
| 665 | # |
| 666 | # ==== Options |
| 667 | # |
| 668 | # +id+ Can be either an Integer or an Array of Integers |
| 669 | # |
| 670 | # ==== Examples |
| 671 | # |
| 672 | # # Destroy a single object |
| 673 | # Todo.destroy(1) |
| 674 | # |
| 675 | # # Destroy multiple objects |
| 676 | # todos = [1,2,3] |
| 677 | # Todo.destroy(todos) |
| 678 | def destroy(id) |
| 679 | if id.is_a?(Array) |
| 680 | id.map { |one_id| destroy(one_id) } |
| 681 | else |
| 682 | find(id).destroy |
| 683 | end |
| 684 | end |
| 685 | |
| 686 | # Updates all records with details given if they match a set of conditions supplied, limits and order can |
| 687 | # also be supplied. |
| 688 | # |
| 689 | # ==== Options |
| 690 | # |
| 691 | # +updates+ A String of column and value pairs that will be set on any records that match conditions |
| 692 | # +conditions+ An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. |
| 693 | # See conditions in the intro for more info. |
| 694 | # +options+ Additional options are :limit and/or :order, see the examples for usage. |
| 695 | # |
| 696 | # ==== Examples |
| 697 | # |
| 698 | # # Update all billing objects with the 3 different attributes given |
| 699 | # Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" ) |
| 700 | # |
| 701 | # # Update records that match our conditions |
| 702 | # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" ) |
| 703 | # |
| 704 | # # Update records that match our conditions but limit it to 5 ordered by date |
| 705 | # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'", |
| 706 | # :order => 'created_at', :limit => 5 ) |
| 707 | def update_all(updates, conditions = nil, options = {}) |
| 708 | sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} " |
| 709 | scope = scope(:find) |
| 710 | add_conditions!(sql, conditions, scope) |
| 711 | add_order!(sql, options[:order], nil) |
| 712 | add_limit!(sql, options, nil) |
| 713 | connection.update(sql, "#{name} Update") |
| 714 | end |
| 715 | |
| 716 | # Destroys the records matching +conditions+ by instantiating each record and calling the destroy method. |
| 717 | # This means at least 2*N database queries to destroy N records, so avoid destroy_all if you are deleting |
| 718 | # many records. If you want to simply delete records without worrying about dependent associations or |
| 719 | # callbacks, use the much faster +delete_all+ method instead. |
| 720 | # |
| 721 | # ==== Options |
| 722 | # |
| 723 | # +conditions+ Conditions are specified the same way as with +find+ method. |
| 724 | # |
| 725 | # ==== Example |
| 726 | # |
| 727 | # Person.destroy_all "last_login < '2004-04-04'" |
| 728 | # |
| 729 | # This loads and destroys each person one by one, including its dependent associations and before_ and |
| 730 | # after_destroy callbacks. |
| 731 | def destroy_all(conditions = nil) |
| 732 | find(:all, :conditions => conditions).each { |object| object.destroy } |
| 733 | end |
| 734 | |
| 735 | # Deletes the records matching +conditions+ without instantiating the records first, and hence not |
| 736 | # calling the destroy method and invoking callbacks. This is a single SQL query, much more efficient |
| 737 | # than destroy_all. |
| 738 | # |
| 739 | # ==== Options |
| 740 | # |
| 741 | # +conditions+ Conditions are specified the same way as with +find+ method. |
| 742 | # |
| 743 | # ==== Example |
| 744 | # |
| 745 | # Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')" |
| 746 | # |
| 747 | # This deletes the affected posts all at once with a single DELETE query. If you need to destroy dependent |
| 748 | # associations or call your before_ or after_destroy callbacks, use the +destroy_all+ method instead. |
| 749 | def delete_all(conditions = nil) |
| 750 | sql = "DELETE FROM #{quoted_table_name} " |
| 751 | add_conditions!(sql, conditions, scope(:find)) |
| 752 | connection.delete(sql, "#{name} Delete all") |
| 753 | end |
| 754 | |
| 755 | # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. |
| 756 | # The use of this method should be restricted to complicated SQL queries that can't be executed |
| 757 | # using the ActiveRecord::Calculations class methods. Look into those before using this. |
| 758 | # |
| 759 | # ==== Options |
| 760 | # |
| 761 | # +sql+: An SQL statement which should return a count query from the database, see the example below |
| 762 | # |
| 763 | # ==== Examples |
| 764 | # |
| 765 | # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" |
| 766 | def count_by_sql(sql) |
| 767 | sql = sanitize_conditions(sql) |
| 768 | connection.select_value(sql, "#{name} Count").to_i |
| 769 | end |
| 770 | |
| 771 | # A generic "counter updater" implementation, intended primarily to be |
| 772 | # used by increment_counter and decrement_counter, but which may also |
| 773 | # be useful on its own. It simply does a direct SQL update for the record |
| 774 | # with the given ID, altering the given hash of counters by the amount |
| 775 | # given by the corresponding value: |
| 776 | # |
| 777 | # ==== Options |
| 778 | # |
| 779 | # +id+ The id of the object you wish to update a counter on |
| 780 | # +counters+ An Array of Hashes containing the names of the fields |
| 781 | # to update as keys and the amount to update the field by as |
| 782 | # values |
| 783 | # |
| 784 | # ==== Examples |
| 785 | # |
| 786 | # # For the Post with id of 5, decrement the comment_count by 1, and |
| 787 | # # increment the action_count by 1 |
| 788 | # Post.update_counters 5, :comment_count => -1, :action_count => 1 |
| 789 | # # Executes the following SQL: |
| 790 | # # UPDATE posts |
| 791 | # # SET comment_count = comment_count - 1, |
| 792 | # # action_count = action_count + 1 |
| 793 | # # WHERE id = 5 |
| 794 | def update_counters(id, counters) |
| 795 | updates = counters.inject([]) { |list, (counter_name, increment)| |
| 796 | sign = increment < 0 ? "-" : "+" |
| 797 | list << "#{connection.quote_column_name(counter_name)} = #{connection.quote_column_name(counter_name)} #{sign} #{increment.abs}" |
| 798 | }.join(", ") |
| 799 | update_all(updates, "#{connection.quote_column_name(primary_key)} = #{quote_value(id)}") |
| 800 | end |
| 801 | |
| 802 | # Increment a number field by one, usually representing a count. |
| 803 | # |
| 804 | # This is used for caching aggregate values, so that they don't need to be computed every time. |
| 805 | # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is |
| 806 | # shown it would have to run an SQL query to find how many posts and comments there are. |
| 807 | # |
| 808 | # ==== Options |
| 809 | # |
| 810 | # +counter_name+ The name of the field that should be incremented |
| 811 | # +id+ The id of the object that should be incremented |
| 812 | # |
| 813 | # ==== Examples |
| 814 | # |
| 815 | # # Increment the post_count column for the record with an id of 5 |
| 816 | # DiscussionBoard.increment_counter(:post_count, 5) |
| 817 | def increment_counter(counter_name, id) |
| 818 | update_counters(id, counter_name => 1) |
| 819 | end |
| 820 | |
| 821 | # Decrement a number field by one, usually representing a count. |
| 822 | # |
| 823 | # This works the same as increment_counter but reduces the column value by 1 instead of increasing it. |
| 824 | # |
| 825 | # ==== Options |
| 826 | # |
| 827 | # +counter_name+ The name of the field that should be decremented |
| 828 | # +id+ The id of the object that should be decremented |
| 829 | # |
| 830 | # ==== Examples |
| 831 | # |
| 832 | # # Decrement the post_count column for the record with an id of 5 |
| 833 | # DiscussionBoard.decrement_counter(:post_count, 5) |
| 834 | def decrement_counter(counter_name, id) |
| 835 | update_counters(id, counter_name => -1) |
| 836 | end |
| 837 | |
| 838 | |
| 839 | # Attributes named in this macro are protected from mass-assignment, such as <tt>new(attributes)</tt> and |
| 840 | # <tt>attributes=(attributes)</tt>. Their assignment will simply be ignored. Instead, you can use the direct writer |
| 841 | # methods to do assignment. This is meant to protect sensitive attributes from being overwritten by URL/form hackers. Example: |
| 842 | # |
| 843 | # class Customer < ActiveRecord::Base |
| 844 | # attr_protected :credit_rating |
| 845 | # end |
| 846 | # |
| 847 | # customer = Customer.new("name" => David, "credit_rating" => "Excellent") |
| 848 | # customer.credit_rating # => nil |
| 849 | # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" } |
| 850 | # customer.credit_rating # => nil |
| 851 | # |
| 852 | # customer.credit_rating = "Average" |
| 853 | # customer.credit_rating # => "Average" |
| 854 | # |
| 855 | # To start from an all-closed default and enable attributes as needed, have a look at attr_accessible. |
| 856 | def attr_protected(*attributes) |
| 857 | write_inheritable_attribute("attr_protected", Set.new(attributes.map(&:to_s)) + (protected_attributes || [])) |
| 858 | end |
| 859 | |
| 860 | # Returns an array of all the attributes that have been protected from mass-assignment. |
| 861 | def protected_attributes # :nodoc: |
| 862 | read_inheritable_attribute("attr_protected") |
| 863 | end |
| 864 | |
| 865 | # Similar to the attr_protected macro, this protects attributes of your model from mass-assignment, |
| 866 | # such as <tt>new(attributes)</tt> and <tt>attributes=(attributes)</tt> |
| 867 | # however, it does it in the opposite way. This locks all attributes and only allows access to the |
| 868 | # attributes specified. Assignment to attributes not in this list will be ignored and need to be set |
| 869 | # using the direct writer methods instead. This is meant to protect sensitive attributes from being |
| 870 | # overwritten by URL/form hackers. If you'd rather start from an all-open default and restrict |
| 871 | # attributes as needed, have a look at attr_protected. |
| 872 | # |
| 873 | # ==== Options |
| 874 | # |
| 875 | # <tt>*attributes</tt> A comma separated list of symbols that represent columns _not_ to be protected |
| 876 | # |
| 877 | # ==== Examples |
| 878 | # |
| 879 | # class Customer < ActiveRecord::Base |
| 880 | # attr_accessible :name, :nickname |
| 881 | # end |
| 882 | # |
| 883 | # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent") |
| 884 | # customer.credit_rating # => nil |
| 885 | # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" } |
| 886 | # customer.credit_rating # => nil |
| 887 | # |
| 888 | # customer.credit_rating = "Average" |
| 889 | # customer.credit_rating # => "Average" |
| 890 | def attr_accessible(*attributes) |
| 891 | write_inheritable_attribute("attr_accessible", Set.new(attributes.map(&:to_s)) + (accessible_attributes || [])) |
| 892 | end |
| 893 | |
| 894 | # Returns an array of all the attributes that have been made accessible to mass-assignment. |
| 895 | def accessible_attributes # :nodoc: |
| 896 | read_inheritable_attribute("attr_accessible") |
| 897 | end |
| 898 | |
| 899 | # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards. |
| 900 | def attr_readonly(*attributes) |
| 901 | write_inheritable_attribute("attr_readonly", Set.new(attributes.map(&:to_s)) + (readonly_attributes || [])) |
| 902 | end |
| 903 | |
| 904 | # Returns an array of all the attributes that have been specified as readonly. |
| 905 | def readonly_attributes |
| 906 | read_inheritable_attribute("attr_readonly") |
| 907 | end |
| 908 | |
| 909 | # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, |
| 910 | # then specify the name of that attribute using this method and it will be handled automatically. |
| 911 | # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that |
| 912 | # class on retrieval or +SerializationTypeMismatch+ will be raised. |
| 913 | # |
| 914 | # ==== Options |
| 915 | # |
| 916 | # +attr_name+ The field name that should be serialized |
| 917 | # +class_name+ Optional, class name that the object type should be equal to |
| 918 | # |
| 919 | # ==== Example |
| 920 | # # Serialize a preferences attribute |
| 921 | # class User |
| 922 | # serialize :preferences |
| 923 | # end |
| 924 | def serialize(attr_name, class_name = Object) |
| 925 | serialized_attributes[attr_name.to_s] = class_name |
| 926 | end |
| 927 | |
| 928 | # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values. |
| 929 | def serialized_attributes |
| 930 | read_inheritable_attribute("attr_serialized") or write_inheritable_attribute("attr_serialized", {}) |
| 931 | end |
| 932 | |
| 933 | |
| 934 | # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending |
| 935 | # directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used |
| 936 | # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class |
| 937 | # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb. |
| 938 | # |
| 939 | # Nested classes are given table names prefixed by the singular form of |
| 940 | # the parent's table name. Enclosing modules are not considered. Examples: |
| 941 | # |
| 942 | # class Invoice < ActiveRecord::Base; end; |
| 943 | # file class table_name |
| 944 | # invoice.rb Invoice invoices |
| 945 | # |
| 946 | # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end; |
| 947 | # file class table_name |
| 948 | # invoice.rb Invoice::Lineitem invoice_lineitems |
| 949 | # |
| 950 | # module Invoice; class Lineitem < ActiveRecord::Base; end; end; |
| 951 | # file class table_name |
| 952 | # invoice/lineitem.rb Invoice::Lineitem lineitems |
| 953 | # |
| 954 | # Additionally, the class-level table_name_prefix is prepended and the |
| 955 | # table_name_suffix is appended. So if you have "myapp_" as a prefix, |
| 956 | # the table name guess for an Invoice class becomes "myapp_invoices". |
| 957 | # Invoice::Lineitem becomes "myapp_invoice_lineitems". |
| 958 | # |
| 959 | # You can also overwrite this class method to allow for unguessable |
| 960 | # links, such as a Mouse class with a link to a "mice" table. Example: |
| 961 | # |
| 962 | # class Mouse < ActiveRecord::Base |
| 963 | # set_table_name "mice" |
| 964 | # end |
| 965 | def table_name |
| 966 | reset_table_name |
| 967 | end |
| 968 | |
| 969 | def reset_table_name #:nodoc: |
| 970 | base = base_class |
| 971 | |
| 972 | name = |
| 973 | # STI subclasses always use their superclass' table. |
| 974 | unless self == base |
| 975 | base.table_name |
| 976 | else |
| 977 | # Nested classes are prefixed with singular parent table name. |
| 978 | if parent < ActiveRecord::Base && !parent.abstract_class? |
| 979 | contained = parent.table_name |
| 980 | contained = contained.singularize if parent.pluralize_table_names |
| 981 | contained << '_' |
| 982 | end |
| 983 | name = "#{table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}" |
| 984 | end |
| 985 | |
| 986 | set_table_name(name) |
| 987 | name |
| 988 | end |
| 989 | |
| 990 | # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the |
| 991 | # primary_key_prefix_type setting, though. |
| 992 | def primary_key |
| 993 | reset_primary_key |
| 994 | end |
| 995 | |
| 996 | def reset_primary_key #:nodoc: |
| 997 | key = get_primary_key(base_class.name) |
| 998 | set_primary_key(key) |
| 999 | key |
| 1000 | end |
| 1001 | |
| 1002 | def get_primary_key(base_name) #:nodoc: |
| 1003 | key = 'id' |
| 1004 | case primary_key_prefix_type |
| 1005 | when :table_name |
| 1006 | key = Inflector.foreign_key(base_name, false) |
| 1007 | when :table_name_with_underscore |
| 1008 | key = Inflector.foreign_key(base_name) |
| 1009 | end |
| 1010 | key |
| 1011 | end |
| 1012 | |
| 1013 | # Defines the column name for use with single table inheritance |
| 1014 | # -- can be set in subclasses like so: self.inheritance_column = "type_id" |
| 1015 | def inheritance_column |
| 1016 | @inheritance_column ||= "type".freeze |
| 1017 | end |
| 1018 | |
| 1019 | # Lazy-set the sequence name to the connection's default. This method |
| 1020 | # is only ever called once since set_sequence_name overrides it. |
| 1021 | def sequence_name #:nodoc: |
| 1022 | reset_sequence_name |
| 1023 | end |
| 1024 | |
| 1025 | def reset_sequence_name #:nodoc: |
| 1026 | default = connection.default_sequence_name(table_name, primary_key) |
| 1027 | set_sequence_name(default) |
| 1028 | default |
| 1029 | end |
| 1030 | |
| 1031 | # Sets the table name to use to the given value, or (if the value |
| 1032 | # is nil or false) to the value returned by the given block. |
| 1033 | # |
| 1034 | # Example: |
| 1035 | # |
| 1036 | # class Project < ActiveRecord::Base |
| 1037 | # set_table_name "project" |
| 1038 | # end |
| 1039 | def set_table_name(value = nil, &block) |
| 1040 | define_attr_method :table_name, value, &block |
| 1041 | end |
| 1042 | alias :table_name= :set_table_name |
| 1043 | |
| 1044 | # Sets the name of the primary key column to use to the given value, |
| 1045 | # or (if the value is nil or false) to the value returned by the given |
| 1046 | # block. |
| 1047 | # |
| 1048 | # Example: |
| 1049 | # |
| 1050 | # class Project < ActiveRecord::Base |
| 1051 | # set_primary_key "sysid" |
| 1052 | # end |
| 1053 | def set_primary_key(value = nil, &block) |
| 1054 | define_attr_method :primary_key, value, &block |
| 1055 | end |
| 1056 | alias :primary_key= :set_primary_key |
| 1057 | |
| 1058 | # Sets the name of the inheritance column to use to the given value, |
| 1059 | # or (if the value # is nil or false) to the value returned by the |
| 1060 | # given block. |
| 1061 | # |
| 1062 | # Example: |
| 1063 | # |
| 1064 | # class Project < ActiveRecord::Base |
| 1065 | # set_inheritance_column do |
| 1066 | # original_inheritance_column + "_id" |
| 1067 | # end |
| 1068 | # end |
| 1069 | def set_inheritance_column(value = nil, &block) |
| 1070 | define_attr_method :inheritance_column, value, &block |
| 1071 | end |
| 1072 | alias :inheritance_column= :set_inheritance_column |
| 1073 | |
| 1074 | # Sets the name of the sequence to use when generating ids to the given |
| 1075 | # value, or (if the value is nil or false) to the value returned by the |
| 1076 | # given block. This is required for Oracle and is useful for any |
| 1077 | # database which relies on sequences for primary key generation. |
| 1078 | # |
| 1079 | # If a sequence name is not explicitly set when using Oracle or Firebird, |
| 1080 | # it will default to the commonly used pattern of: #{table_name}_seq |
| 1081 | # |
| 1082 | # If a sequence name is not explicitly set when using PostgreSQL, it |
| 1083 | # will discover the sequence corresponding to your primary key for you. |
| 1084 | # |
| 1085 | # Example: |
| 1086 | # |
| 1087 | # class Project < ActiveRecord::Base |
| 1088 | # set_sequence_name "projectseq" # default would have been "project_seq" |
| 1089 | # end |
| 1090 | def set_sequence_name(value = nil, &block) |
| 1091 | define_attr_method :sequence_name, value, &block |
| 1092 | end |
| 1093 | alias :sequence_name= :set_sequence_name |
| 1094 | |
| 1095 | # Turns the +table_name+ back into a class name following the reverse rules of +table_name+. |
| 1096 | def class_name(table_name = table_name) # :nodoc: |
| 1097 | # remove any prefix and/or suffix from the table name |
| 1098 | class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize |
| 1099 | class_name = class_name.singularize if pluralize_table_names |
| 1100 | class_name |
| 1101 | end |
| 1102 | |
| 1103 | # Indicates whether the table associated with this class exists |
| 1104 | def table_exists? |
| 1105 | if connection.respond_to?(:tables) |
| 1106 | connection.tables.include? table_name |
| 1107 | else |
| 1108 | # if the connection adapter hasn't implemented tables, there are two crude tests that can be |
| 1109 | # used - see if getting column info raises an error, or if the number of columns returned is zero |
| 1110 | begin |
| 1111 | reset_column_information |
| 1112 | columns.size > 0 |
| 1113 | rescue ActiveRecord::StatementInvalid |
| 1114 | false |
| 1115 | end |
| 1116 | end |
| 1117 | end |
| 1118 | |
| 1119 | # Returns an array of column objects for the table associated with this class. |
| 1120 | def columns |
| 1121 | unless defined?(@columns) && @columns |
| 1122 | @columns = connection.columns(table_name, "#{name} Columns") |
| 1123 | @columns.each { |column| column.primary = column.name == primary_key } |
| 1124 | end |
| 1125 | @columns |
| 1126 | end |
| 1127 | |
| 1128 | # Returns a hash of column objects for the table associated with this class. |
| 1129 | def columns_hash |
| 1130 | @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash } |
| 1131 | end |
| 1132 | |
| 1133 | # Returns an array of column names as strings. |
| 1134 | def column_names |
| 1135 | @column_names ||= columns.map { |column| column.name } |
| 1136 | end |
| 1137 | |
| 1138 | # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", |
| 1139 | # and columns used for single table inheritance have been removed. |
| 1140 | def content_columns |
| 1141 | @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column } |
| 1142 | end |
| 1143 | |
| 1144 | # 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 |
| 1145 | # 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 |
| 1146 | # is available. |
| 1147 | def column_methods_hash #:nodoc: |
| 1148 | @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr| |
| 1149 | attr_name = attr.to_s |
| 1150 | methods[attr.to_sym] = attr_name |
| 1151 | methods["#{attr}=".to_sym] = attr_name |
| 1152 | methods["#{attr}?".to_sym] = attr_name |
| 1153 | methods["#{attr}_before_type_cast".to_sym] = attr_name |
| 1154 | methods |
| 1155 | end |
| 1156 | end |
| 1157 | |
| 1158 | # Resets all the cached information about columns, which will cause them to be reloaded on the next request. |
| 1159 | def reset_column_information |
| 1160 | generated_methods.each { |name| undef_method(name) } |
| 1161 | @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @generated_methods = @inheritance_column = nil |
| 1162 | end |
| 1163 | |
| 1164 | def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc: |
| 1165 | subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information } |
| 1166 | end |
| 1167 | |
| 1168 | # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example: |
| 1169 | # Person.human_attribute_name("first_name") # => "First name" |
| 1170 | # Deprecated in favor of just calling "first_name".humanize |
| 1171 | def human_attribute_name(attribute_key_name) #:nodoc: |
| 1172 | attribute_key_name.humanize |
| 1173 | end |
| 1174 | |
| 1175 | # True if this isn't a concrete subclass needing a STI type condition. |
| 1176 | def descends_from_active_record? |
| 1177 | if superclass.abstract_class? |
| 1178 | superclass.descends_from_active_record? |
| 1179 | else |
| 1180 | superclass == Base || !columns_hash.include?(inheritance_column) |
| 1181 | end |
| 1182 | end |
| 1183 | |
| 1184 | def finder_needs_type_condition? #:nodoc: |
| 1185 | # This is like this because benchmarking justifies the strange :false stuff |
| 1186 | :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) |
| 1187 | end |
| 1188 | |
| 1189 | # Returns a string like 'Post id:integer, title:string, body:text' |
| 1190 | def inspect |
| 1191 | if self == Base |
| 1192 | super |
| 1193 | elsif abstract_class? |
| 1194 | "#{super}(abstract)" |
| 1195 | elsif table_exists? |
| 1196 | attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', ' |
| 1197 | "#{super}(#{attr_list})" |
| 1198 | else |
| 1199 | "#{super}(Table doesn't exist)" |
| 1200 | end |
| 1201 | end |
| 1202 | |
| 1203 | |
| 1204 | def quote_value(value, column = nil) #:nodoc: |
| 1205 | connection.quote(value,column) |
| 1206 | end |
| 1207 | |
| 1208 | # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>. |
| 1209 | def sanitize(object) #:nodoc: |
| 1210 | connection.quote(object) |
| 1211 | end |
| 1212 | |
| 1213 | # Log and benchmark multiple statements in a single block. Example: |
| 1214 | # |
| 1215 | # Project.benchmark("Creating project") do |
| 1216 | # project = Project.create("name" => "stuff") |
| 1217 | # project.create_manager("name" => "David") |
| 1218 | # project.milestones << Milestone.find(:all) |
| 1219 | # end |
| 1220 | # |
| 1221 | # The benchmark is only recorded if the current level of the logger is less than or equal to the <tt>log_level</tt>, |
| 1222 | # which makes it easy to include benchmarking statements in production software that will remain inexpensive because |
| 1223 | # the benchmark will only be conducted if the log level is low enough. |
| 1224 | # |
| 1225 | # The logging of the multiple statements is turned off unless <tt>use_silence</tt> is set to false. |
| 1226 | def benchmark(title, log_level = Logger::DEBUG, use_silence = true) |
| 1227 | if logger && logger.level <= log_level |
| 1228 | result = nil |
| 1229 | seconds = Benchmark.realtime { result = use_silence ? silence { yield } : yield } |
| 1230 | logger.add(log_level, "#{title} (#{'%.5f' % seconds})") |
| 1231 | result |
| 1232 | else |
| 1233 | yield |
| 1234 | end |
| 1235 | end |
| 1236 | |
| 1237 | # Silences the logger for the duration of the block. |
| 1238 | def silence |
| 1239 | old_logger_level, logger.level = logger.level, Logger::ERROR if logger |
| 1240 | yield |
| 1241 | ensure |
| 1242 | logger.level = old_logger_level if logger |
| 1243 | end |
| 1244 | |
| 1245 | # Overwrite the default class equality method to provide support for association proxies. |
| 1246 | def ===(object) |
| 1247 | object.is_a?(self) |
| 1248 | end |
| 1249 | |
| 1250 | # Returns the base AR subclass that this class descends from. If A |
| 1251 | # extends AR::Base, A.base_class will return A. If B descends from A |
| 1252 | # through some arbitrarily deep hierarchy, B.base_class will return A. |
| 1253 | def base_class |
| 1254 | class_of_active_record_descendant(self) |
| 1255 | end |
| 1256 | |
| 1257 | # Set this to true if this is an abstract class (see #abstract_class?). |
| 1258 | attr_accessor :abstract_class |
| 1259 | |
| 1260 | # Returns whether this class is a base AR class. If A is a base class and |
| 1261 | # B descends from A, then B.base_class will return B. |
| 1262 | def abstract_class? |
| 1263 | defined?(@abstract_class) && @abstract_class == true |
| 1264 | end |
| 1265 | |
| 1266 | def respond_to?(method_id, include_private = false) |
| 1267 | if match = matches_dynamic_finder?(method_id) || matches_dynamic_finder_with_initialize_or_create?(method_id) |
| 1268 | return true if all_attributes_exists?(extract_attribute_names_from_match(match)) |
| 1269 | end |
| 1270 | super |
| 1271 | end |
| 1272 | |
| 1273 | private |
| 1274 | def find_initial(options) |
| 1275 | options.update(:limit => 1) unless options[:include] |
| 1276 | find_every(options).first |
| 1277 | end |
| 1278 | |
| 1279 | def find_last(options) |
| 1280 | order = options[:order] |
| 1281 | |
| 1282 | if order |
| 1283 | order = reverse_sql_order(order) |
| 1284 | elsif !scoped?(:find, :order) |
| 1285 | order = "#{table_name}.#{primary_key} DESC" |
| 1286 | end |
| 1287 | |
| 1288 | if scoped?(:find, :order) |
| 1289 | scoped_order = reverse_sql_order(scope(:find, :order)) |
| 1290 | scoped_methods.select { |s| s[:find].update(:order => scoped_order) } |
| 1291 | end |
| 1292 | |
| 1293 | find_initial(options.merge({ :order => order })) |
| 1294 | end |
| 1295 | |
| 1296 | def reverse_sql_order(order_query) |
| 1297 | reversed_query = order_query.split(/,/).each { |s| |
| 1298 | if s.match(/\s(asc|ASC)$/) |
| 1299 | s.gsub!(/\s(asc|ASC)$/, ' DESC') |
| 1300 | elsif s.match(/\s(desc|DESC)$/) |
| 1301 | s.gsub!(/\s(desc|DESC)$/, ' ASC') |
| 1302 | elsif !s.match(/\s(asc|ASC|desc|DESC)$/) |
| 1303 | s.concat(' DESC') |
| 1304 | end |
| 1305 | }.join(',') |
| 1306 | end |
| 1307 | |
| 1308 | def find_every(options) |
| 1309 | include_associations = merge_includes(scope(:find, :include), options[:include]) |
| 1310 | |
| 1311 | if include_associations.any? && references_eager_loaded_tables?(options) |
| 1312 | records = find_with_associations(options) |
| 1313 | else |
| 1314 | records = find_by_sql(construct_finder_sql(options)) |
| 1315 | if include_associations.any? |
| 1316 | preload_associations(records, include_associations) |
| 1317 | end |
| 1318 | end |
| 1319 | |
| 1320 | records.each { |record| record.readonly! } if options[:readonly] |
| 1321 | |
| 1322 | records |
| 1323 | end |
| 1324 | |
| 1325 | def find_from_ids(ids, options) |
| 1326 | expects_array = ids.first.kind_of?(Array) |
| 1327 | return ids.first if expects_array && ids.first.empty? |
| 1328 | |
| 1329 | ids = ids.flatten.compact.uniq |
| 1330 | |
| 1331 | case ids.size |
| 1332 | when 0 |
| 1333 | raise RecordNotFound, "Couldn't find #{name} without an ID" |
| 1334 | when 1 |
| 1335 | result = find_one(ids.first, options) |
| 1336 | expects_array ? [ result ] : result |
| 1337 | else |
| 1338 | find_some(ids, options) |
| 1339 | end |
| 1340 | end |
| 1341 | |
| 1342 | def find_one(id, options) |
| 1343 | conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions] |
| 1344 | options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}" |
| 1345 | |
| 1346 | # Use find_every(options).first since the primary key condition |
| 1347 | # already ensures we have a single record. Using find_initial adds |
| 1348 | # a superfluous :limit => 1. |
| 1349 | if result = find_every(options).first |
| 1350 | result |
| 1351 | else |
| 1352 | raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}" |
| 1353 | end |
| 1354 | end |
| 1355 | |
| 1356 | def find_some(ids, options) |
| 1357 | conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions] |
| 1358 | ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',') |
| 1359 | options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}" |
| 1360 | |
| 1361 | result = find_every(options) |
| 1362 | |
| 1363 | # Determine expected size from limit and offset, not just ids.size. |
| 1364 | expected_size = |
| 1365 | if options[:limit] && ids.size > options[:limit] |
| 1366 | options[:limit] |
| 1367 | else |
| 1368 | ids.size |
| 1369 | end |
| 1370 | |
| 1371 | # 11 ids with limit 3, offset 9 should give 2 results. |
| 1372 | if options[:offset] && (ids.size - options[:offset] < expected_size) |
| 1373 | expected_size = ids.size - options[:offset] |
| 1374 | end |
| 1375 | |
| 1376 | if result.size == expected_size |
| 1377 | result |
| 1378 | else |
| 1379 | raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions} (found #{result.size} results, but was looking for #{expected_size})" |
| 1380 | end |
| 1381 | end |
| 1382 | |
| 1383 | # Finder methods must instantiate through this method to work with the |
| 1384 | # single-table inheritance model that makes it possible to create |
| 1385 | # objects of different types from the same table. |
| 1386 | def instantiate(record) |
| 1387 | object = |
| 1388 | if subclass_name = record[inheritance_column] |
| 1389 | # No type given. |
| 1390 | if subclass_name.empty? |
| 1391 | allocate |
| 1392 | |
| 1393 | else |
| 1394 | # Ignore type if no column is present since it was probably |
| 1395 | # pulled in from a sloppy join. |
| 1396 | unless columns_hash.include?(inheritance_column) |
| 1397 | allocate |
| 1398 | |
| 1399 | else |
| 1400 | begin |
| 1401 | compute_type(subclass_name).allocate |
| 1402 | rescue NameError |
| 1403 | raise SubclassNotFound, |
| 1404 | "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " + |
| 1405 | "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + |
| 1406 | "Please rename this column if you didn't intend it to be used for storing the inheritance class " + |
| 1407 | "or overwrite #{self.to_s}.inheritance_column to use another column for that information." |
| 1408 | end |
| 1409 | end |
| 1410 | end |
| 1411 | else |
| 1412 | allocate |
| 1413 | end |
| 1414 | |
| 1415 | object.instance_variable_set("@attributes", record) |
| 1416 | object.instance_variable_set("@attributes_cache", Hash.new) |
| 1417 | |
| 1418 | if object.respond_to_without_attributes?(:after_find) |
| 1419 | object.send(:callback, :after_find) |
| 1420 | end |
| 1421 | |
| 1422 | if object.respond_to_without_attributes?(:after_initialize) |
| 1423 | object.send(:callback, :after_initialize) |
| 1424 | end |
| 1425 | |
| 1426 | object |
| 1427 | end |
| 1428 | |
| 1429 | # Nest the type name in the same module as this class. |
| 1430 | # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo |
| 1431 | def type_name_with_module(type_name) |
| 1432 | (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}" |
| 1433 | end |
| 1434 | |
| 1435 | def construct_finder_sql(options) |
| 1436 | scope = scope(:find) |
| 1437 | sql = "SELECT #{(scope && scope[:select]) || options[:select] || (options[:joins] && quoted_table_name + '.*') || '*'} " |
| 1438 | sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " |
| 1439 | |
| 1440 | add_joins!(sql, options, scope) |
| 1441 | add_conditions!(sql, options[:conditions], scope) |
| 1442 | |
| 1443 | add_group!(sql, options[:group], scope) |
| 1444 | add_order!(sql, options[:order], scope) |
| 1445 | add_limit!(sql, options, scope) |
| 1446 | add_lock!(sql, options, scope) |
| 1447 | |
| 1448 | sql |
| 1449 | end |
| 1450 | |
| 1451 | # Merges includes so that the result is a valid +include+ |
| 1452 | def merge_includes(first, second) |
| 1453 | (safe_to_array(first) + safe_to_array(second)).uniq |
| 1454 | end |
| 1455 | |
| 1456 | # Merges conditions so that the result is a valid +condition+ |
| 1457 | def merge_conditions(*conditions) |
| 1458 | segments = [] |
| 1459 | |
| 1460 | conditions.each do |condition| |
| 1461 | unless condition.blank? |
| 1462 | sql = sanitize_sql(condition) |
| 1463 | segments << sql unless sql.blank? |
| 1464 | end |
| 1465 | end |
| 1466 | |
| 1467 | "(#{segments.join(') AND (')})" unless segments.empty? |
| 1468 | end |
| 1469 | |
| 1470 | # Object#to_a is deprecated, though it does have the desired behavior |
| 1471 | def safe_to_array(o) |
| 1472 | case o |
| 1473 | when NilClass |
| 1474 | [] |
| 1475 | when Array |
| 1476 | o |
| 1477 | else |
| 1478 | [o] |
| 1479 | end |
| 1480 | end |
| 1481 | |
| 1482 | def add_order!(sql, order, scope = :auto) |
| 1483 | scope = scope(:find) if :auto == scope |
| 1484 | scoped_order = scope[:order] if scope |
| 1485 | if order |
| 1486 | sql << " ORDER BY #{order}" |
| 1487 | sql << ", #{scoped_order}" if scoped_order |
| 1488 | else |
| 1489 | sql << " ORDER BY #{scoped_order}" if scoped_order |
| 1490 | end |
| 1491 | end |
| 1492 | |
| 1493 | def add_group!(sql, group, scope = :auto) |
| 1494 | if group |
| 1495 | sql << " GROUP BY #{group}" |
| 1496 | else |
| 1497 | scope = scope(:find) if :auto == scope |
| 1498 | if scope && (scoped_group = scope[:group]) |
| 1499 | sql << " GROUP BY #{scoped_group}" |
| 1500 | end |
| 1501 | end |
| 1502 | end |
| 1503 | |
| 1504 | # The optional scope argument is for the current :find scope. |
| 1505 | def add_limit!(sql, options, scope = :auto) |
| 1506 | scope = scope(:find) if :auto == scope |
| 1507 | |
| 1508 | if scope |
| 1509 | options[:limit] ||= scope[:limit] |
| 1510 | options[:offset] ||= scope[:offset] |
| 1511 | end |
| 1512 | |
| 1513 | connection.add_limit_offset!(sql, options) |
| 1514 | end |
| 1515 | |
| 1516 | # The optional scope argument is for the current :find scope. |
| 1517 | # The :lock option has precedence over a scoped :lock. |
| 1518 | def add_lock!(sql, options, scope = :auto) |
| 1519 | scope = scope(:find) if :auto == scope |
| 1520 | options = options.reverse_merge(:lock => scope[:lock]) if scope |
| 1521 | connection.add_lock!(sql, options) |
| 1522 | end |
| 1523 | |
| 1524 | # The optional scope argument is for the current :find scope. |
| 1525 | def add_joins!(sql, options, scope = :auto) |
| 1526 | scope = scope(:find) if :auto == scope |
| 1527 | [(scope && scope[:joins]), options[:joins]].each do |join| |
| 1528 | case join |
| 1529 | when Symbol, Hash, Array |
| 1530 | join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil) |
| 1531 | sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} " |
| 1532 | else |
| 1533 | sql << " #{join} " |
| 1534 | end |
| 1535 | end |
| 1536 | end |
| 1537 | |
| 1538 | # Adds a sanitized version of +conditions+ to the +sql+ string. Note that the passed-in +sql+ string is changed. |
| 1539 | # The optional scope argument is for the current :find scope. |
| 1540 | def add_conditions!(sql, conditions, scope = :auto) |
| 1541 | scope = scope(:find) if :auto == scope |
| 1542 | conditions = [conditions] |
| 1543 | conditions << scope[:conditions] if scope |
| 1544 | conditions << type_condition if finder_needs_type_condition? |
| 1545 | merged_conditions = merge_conditions(*conditions) |
| 1546 | sql << "WHERE #{merged_conditions} " unless merged_conditions.blank? |
| 1547 | end |
| 1548 | |
| 1549 | def type_condition |
| 1550 | quoted_inheritance_column = connection.quote_column_name(inheritance_column) |
| 1551 | type_condition = subclasses.inject("#{quoted_table_name}.#{quoted_inheritance_column} = '#{name.demodulize}' ") do |condition, subclass| |
| 1552 | condition << "OR #{quoted_table_name}.#{quoted_inheritance_column} = '#{subclass.name.demodulize}' " |
| 1553 | end |
| 1554 | |
| 1555 | " (#{type_condition}) " |
| 1556 | end |
| 1557 | |
| 1558 | # Guesses the table name, but does not decorate it with prefix and suffix information. |
| 1559 | def undecorated_table_name(class_name = base_class.name) |
| 1560 | table_name = Inflector.underscore(Inflector.demodulize(class_name)) |
| 1561 | table_name = Inflector.pluralize(table_name) if pluralize_table_names |
| 1562 | table_name |
| 1563 | end |
| 1564 | |
| 1565 | # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into |
| 1566 | # find(:first, :conditions => ["user_name = ?", user_name]) and find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password]) |
| 1567 | # respectively. Also works for find(:all) by using find_all_by_amount(50) that is turned into find(:all, :conditions => ["amount = ?", 50]). |
| 1568 | # |
| 1569 | # It's even possible to use all the additional parameters to find. For example, the full interface for find_all_by_amount |
| 1570 | # is actually find_all_by_amount(amount, options). |
| 1571 | # |
| 1572 | # This also enables you to initialize a record if it is not found, such as find_or_initialize_by_amount(amount) |
| 1573 | # or find_or_create_by_user_and_password(user, password). |
| 1574 | # |
| 1575 | # Each dynamic finder or initializer/creator is also defined in the class after it is first invoked, so that future |
| 1576 | # attempts to use it do not run through method_missing. |
| 1577 | def method_missing(method_id, *arguments) |
| 1578 | if match = matches_dynamic_finder?(method_id) |
| 1579 | finder = determine_finder(match) |
| 1580 | |
| 1581 | attribute_names = extract_attribute_names_from_match(match) |
| 1582 | super unless all_attributes_exists?(attribute_names) |
| 1583 | |
| 1584 | self.class_eval %{ |
| 1585 | def self.#{method_id}(*args) |
| 1586 | options = args.extract_options! |
| 1587 | attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args) |
| 1588 | finder_options = { :conditions => attributes } |
| 1589 | validate_find_options(options) |
| 1590 | set_readonly_option!(options) |
| 1591 | |
| 1592 | if options[:conditions] |
| 1593 | with_scope(:find => finder_options) do |
| 1594 | ActiveSupport::Deprecation.silence { send(:#{finder}, options) } |
| 1595 | end |
| 1596 | else |
| 1597 | ActiveSupport::Deprecation.silence { send(:#{finder}, options.merge(finder_options)) } |
| 1598 | end |
| 1599 | end |
| 1600 | }, __FILE__, __LINE__ |
| 1601 | send(method_id, *arguments) |
| 1602 | elsif match = matches_dynamic_finder_with_initialize_or_create?(method_id) |
| 1603 | instantiator = determine_instantiator(match) |
| 1604 | attribute_names = extract_attribute_names_from_match(match) |
| 1605 | super unless all_attributes_exists?(attribute_names) |
| 1606 | |
| 1607 | self.class_eval %{ |
| 1608 | def self.#{method_id}(*args) |
| 1609 | guard_protected_attributes = false |
| 1610 | |
| 1611 | if args[0].is_a?(Hash) |
| 1612 | guard_protected_attributes = true |
| 1613 | attributes = args[0].with_indifferent_access |
| 1614 | find_attributes = attributes.slice(*[:#{attribute_names.join(',:')}]) |
| 1615 | else |
| 1616 | find_attributes = attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args) |
| 1617 | end |
| 1618 | |
| 1619 | options = { :conditions => find_attributes } |
| 1620 | set_readonly_option!(options) |
| 1621 | |
| 1622 | record = find_initial(options) |
| 1623 | |
| 1624 | if record.nil? |
| 1625 | record = self.new { |r| r.send(:attributes=, attributes, guard_protected_attributes) } |
| 1626 | #{'yield(record) if block_given?'} |
| 1627 | #{'record.save' if instantiator == :create} |
| 1628 | record |
| 1629 | else |
| 1630 | record |
| 1631 | end |
| 1632 | end |
| 1633 | }, __FILE__, __LINE__ |
| 1634 | send(method_id, *arguments) |
| 1635 | else |
| 1636 | super |
| 1637 | end |
| 1638 | end |
| 1639 | |
| 1640 | def matches_dynamic_finder?(method_id) |
| 1641 | /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s) |
| 1642 | end |
| 1643 | |
| 1644 | def matches_dynamic_finder_with_initialize_or_create?(method_id) |
| 1645 | /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s) |
| 1646 | end |
| 1647 | |
| 1648 | def determine_finder(match) |
| 1649 | match.captures.first == 'all_by' ? :find_every : :find_initial |
| 1650 | end |
| 1651 | |
| 1652 | def determine_instantiator(match) |
| 1653 | match.captures.first == 'initialize' ? :new : :create |
| 1654 | end |
| 1655 | |
| 1656 | def extract_attribute_names_from_match(match) |
| 1657 | match.captures.last.split('_and_') |
| 1658 | end |
| 1659 | |
| 1660 | def construct_attributes_from_arguments(attribute_names, arguments) |
| 1661 | attributes = {} |
| 1662 | attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] } |
| 1663 | attributes |
| 1664 | end |
| 1665 | |
| 1666 | # Similar in purpose to +expand_hash_conditions_for_aggregates+. |
| 1667 | def expand_attribute_names_for_aggregates(attribute_names) |
| 1668 | expanded_attribute_names = [] |
| 1669 | attribute_names.each do |attribute_name| |
| 1670 | unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? |
| 1671 | aggregate_mapping(aggregation).each do |field_attr, aggregate_attr| |
| 1672 | expanded_attribute_names << field_attr |
| 1673 | end |
| 1674 | else |
| 1675 | expanded_attribute_names << attribute_name |
| 1676 | end |
| 1677 | end |
| 1678 | expanded_attribute_names |
| 1679 | end |
| 1680 | |
| 1681 | def all_attributes_exists?(attribute_names) |
| 1682 | attribute_names = expand_attribute_names_for_aggregates(attribute_names) |
| 1683 | attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) } |
| 1684 | end |
| 1685 | |
| 1686 | def attribute_condition(argument) |
| 1687 | case argument |
| 1688 | when nil then "IS ?" |
| 1689 | when Array, ActiveRecord::Associations::AssociationCollection then "IN (?)" |
| 1690 | when Range then "BETWEEN ? AND ?" |
| 1691 | else "= ?" |
| 1692 | end |
| 1693 | end |
| 1694 | |
| 1695 | # Interpret Array and Hash as conditions and anything else as an id. |
| 1696 | def expand_id_conditions(id_or_conditions) |
| 1697 | case id_or_conditions |
| 1698 | when Array, Hash then id_or_conditions |
| 1699 | else sanitize_sql(primary_key => id_or_conditions) |
| 1700 | end |
| 1701 | end |
| 1702 | |
| 1703 | |
| 1704 | # Defines an "attribute" method (like #inheritance_column or |
| 1705 | # #table_name). A new (class) method will be created with the |
| 1706 | # given name. If a value is specified, the new method will |
| 1707 | # return that value (as a string). Otherwise, the given block |
| 1708 | # will be used to compute the value of the method. |
| 1709 | # |
| 1710 | # The original method will be aliased, with the new name being |
| 1711 | # prefixed with "original_". This allows the new method to |
| 1712 | # access the original value. |
| 1713 | # |
| 1714 | # Example: |
| 1715 | # |
| 1716 | # class A < ActiveRecord::Base |
| 1717 | # define_attr_method :primary_key, "sysid" |
| 1718 | # define_attr_method( :inheritance_column ) do |
| 1719 | # original_inheritance_column + "_id" |
| 1720 | # end |
| 1721 | # end |
| 1722 | def define_attr_method(name, value=nil, &block) |
| 1723 | sing = class << self; self; end |
| 1724 | sing.send :alias_method, "original_#{name}", name |
| 1725 | if block_given? |
| 1726 | sing.send :define_method, name, &block |
| 1727 | else |
| 1728 | # use eval instead of a block to work around a memory leak in dev |
| 1729 | # mode in fcgi |
| 1730 | sing.class_eval "def #{name}; #{value.to_s.inspect}; end" |
| 1731 | end |
| 1732 | end |
| 1733 | |
| 1734 | protected |
| 1735 | # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash. |
| 1736 | # method_name may be :find or :create. :find parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>, |
| 1737 | # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. :create parameters are an attributes hash. |
| 1738 | # |
| 1739 | # class Article < ActiveRecord::Base |
| 1740 | # def self.create_with_scope |
| 1741 | # with_scope(:find => { :conditions => "blog_id = 1" }, :create => { :blog_id => 1 }) do |
| 1742 | # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 |
| 1743 | # a = create(1) |
| 1744 | # a.blog_id # => 1 |
| 1745 | # end |
| 1746 | # end |
| 1747 | # end |
| 1748 | # |
| 1749 | # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of |
| 1750 | # :conditions and :include options in :find, which are merged. |
| 1751 | # |
| 1752 | # class Article < ActiveRecord::Base |
| 1753 | # def self.find_with_scope |
| 1754 | # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }, :create => { :blog_id => 1 }) do |
| 1755 | # with_scope(:find => { :limit => 10}) |
| 1756 | # find(:all) # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 |
| 1757 | # end |
| 1758 | # with_scope(:find => { :conditions => "author_id = 3" }) |
| 1759 | # find(:all) # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 |
| 1760 | # end |
| 1761 | # end |
| 1762 | # end |
| 1763 | # end |
| 1764 | # |
| 1765 | # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method. |
| 1766 | # |
| 1767 | # class Article < ActiveRecord::Base |
| 1768 | # def self.find_with_exclusive_scope |
| 1769 | # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }) do |
| 1770 | # with_exclusive_scope(:find => { :limit => 10 }) |
| 1771 | # find(:all) # => SELECT * from articles LIMIT 10 |
| 1772 | # end |
| 1773 | # end |
| 1774 | # end |
| 1775 | # end |
| 1776 | def with_scope(method_scoping = {}, action = :merge, &block) |
| 1777 | method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping) |
| 1778 | |
| 1779 | # Dup first and second level of hash (method and params). |
| 1780 | method_scoping = method_scoping.inject({}) do |hash, (method, params)| |
| 1781 | hash[method] = (params == true) ? params : params.dup |
| 1782 | hash |
| 1783 | end |
| 1784 | |
| 1785 | method_scoping.assert_valid_keys([ :find, :create ]) |
| 1786 | |
| 1787 | if f = method_scoping[:find] |
| 1788 | f.assert_valid_keys(VALID_FIND_OPTIONS) |
| 1789 | set_readonly_option! f |
| 1790 | end |
| 1791 | |
| 1792 | # Merge scopings |
| 1793 | if action == :merge && current_scoped_methods |
| 1794 | method_scoping = current_scoped_methods.inject(method_scoping) do |hash, (method, params)| |
| 1795 | case hash[method] |
| 1796 | when Hash |
| 1797 | if method == :find |
| 1798 | (hash[method].keys + params.keys).uniq.each do |key| |
| 1799 | merge = hash[method][key] && params[key] # merge if both scopes have the same key |
| 1800 | if key == :conditions && merge |
| 1801 | hash[method][key] = merge_conditions(params[key], hash[method][key]) |
| 1802 | elsif key == :include && merge |
| 1803 | hash[method][key] = merge_includes(hash[method][key], params[key]).uniq |
| 1804 | else |
| 1805 | hash[method][key] = hash[method][key] || params[key] |
| 1806 | end |
| 1807 | end |
| 1808 | else |
| 1809 | hash[method] = params.merge(hash[method]) |
| 1810 | end |
| 1811 | else |
| 1812 | hash[method] = params |
| 1813 | end |
| 1814 | hash |
| 1815 | end |
| 1816 | end |
| 1817 | |
| 1818 | self.scoped_methods << method_scoping |
| 1819 | |
| 1820 | begin |
| 1821 | yield |
| 1822 | ensure |
| 1823 | self.scoped_methods.pop |
| 1824 | end |
| 1825 | end |
| 1826 | |
| 1827 | # Works like with_scope, but discards any nested properties. |
| 1828 | def with_exclusive_scope(method_scoping = {}, &block) |
| 1829 | with_scope(method_scoping, :overwrite, &block) |
| 1830 | end |
| 1831 | |
| 1832 | def subclasses #:nodoc: |
| 1833 | @@subclasses[self] ||= [] |
| 1834 | @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses } |
| 1835 | end |
| 1836 | |
| 1837 | # Test whether the given method and optional key are scoped. |
| 1838 | def scoped?(method, key = nil) #:nodoc: |
| 1839 | if current_scoped_methods && (scope = current_scoped_methods[method]) |
| 1840 | !key || scope.has_key?(key) |
| 1841 | end |
| 1842 | end |
| 1843 | |
| 1844 | # Retrieve the scope for the given method and optional key. |
| 1845 | def scope(method, key = nil) #:nodoc: |
| 1846 | if current_scoped_methods && (scope = current_scoped_methods[method]) |
| 1847 | key ? scope[key] : scope |
| 1848 | end |
| 1849 | end |
| 1850 | |
| 1851 | def thread_safe_scoped_methods #:nodoc: |
| 1852 | scoped_methods = (Thread.current[:scoped_methods] ||= {}) |
| 1853 | scoped_methods[self] ||= [] |
| 1854 | end |
| 1855 | |
| 1856 | def single_threaded_scoped_methods #:nodoc: |
| 1857 | @scoped_methods ||= [] |
| 1858 | end |
| 1859 | |
| 1860 | # pick up the correct scoped_methods version from @@allow_concurrency |
| 1861 | if @@allow_concurrency |
| 1862 | alias_method :scoped_methods, :thread_safe_scoped_methods |
| 1863 | else |
| 1864 | alias_method :scoped_methods, :single_threaded_scoped_methods |
| 1865 | end |
| 1866 | |
| 1867 | def current_scoped_methods #:nodoc: |
| 1868 | scoped_methods.last |
| 1869 | end |
| 1870 | |
| 1871 | # Returns the class type of the record using the current module as a prefix. So descendents of |
| 1872 | # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. |
| 1873 | def compute_type(type_name) |
| 1874 | modularized_name = type_name_with_module(type_name) |
| 1875 | begin |
| 1876 | class_eval(modularized_name, __FILE__, __LINE__) |
| 1877 | rescue NameError |
| 1878 | class_eval(type_name, __FILE__, __LINE__) |
| 1879 | end |
| 1880 | end |
| 1881 | |
| 1882 | # Returns the class descending directly from ActiveRecord in the inheritance hierarchy. |
| 1883 | def class_of_active_record_descendant(klass) |
| 1884 | if klass.superclass == Base || klass.superclass.abstract_class? |
| 1885 | klass |
| 1886 | elsif klass.superclass.nil? |
| 1887 | raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" |
| 1888 | else |
| 1889 | class_of_active_record_descendant(klass.superclass) |
| 1890 | end |
| 1891 | end |
| 1892 | |
| 1893 | # Returns the name of the class descending directly from ActiveRecord in the inheritance hierarchy. |
| 1894 | def class_name_of_active_record_descendant(klass) #:nodoc: |
| 1895 | klass.base_class.name |
| 1896 | end |
| 1897 | |
| 1898 | # Accepts an array, hash, or string of sql conditions and sanitizes |
| 1899 | # them into a valid SQL fragment for a WHERE clause. |
| 1900 | # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" |
| 1901 | # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" |
| 1902 | # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'" |
| 1903 | def sanitize_sql_for_conditions(condition) |
| 1904 | case condition |
| 1905 | when Array; sanitize_sql_array(condition) |
| 1906 | when Hash; sanitize_sql_hash_for_conditions(condition) |
| 1907 | else condition |
| 1908 | end |
| 1909 | end |
| 1910 | alias_method :sanitize_sql, :sanitize_sql_for_conditions |
| 1911 | |
| 1912 | # Accepts an array, hash, or string of sql conditions and sanitizes |
| 1913 | # them into a valid SQL fragment for a SET clause. |
| 1914 | # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'" |
| 1915 | def sanitize_sql_for_assignment(assignments) |
| 1916 | case assignments |
| 1917 | when Array; sanitize_sql_array(assignments) |
| 1918 | when Hash; sanitize_sql_hash_for_assignment(assignments) |
| 1919 | else assignments |
| 1920 | end |
| 1921 | end |
| 1922 | |
| 1923 | def aggregate_mapping(reflection) |
| 1924 | mapping = reflection.options[:mapping] || [reflection.name, reflection.name] |
| 1925 | mapping.first.is_a?(Array) ? mapping : [mapping] |
| 1926 | end |
| 1927 | |
| 1928 | # Accepts a hash of sql conditions and replaces those attributes |
| 1929 | # that correspond to a +composed_of+ relationship with their expanded |
| 1930 | # aggregate attribute values. |
| 1931 | # Given: |
| 1932 | # class Person < ActiveRecord::Base |
| 1933 | # composed_of :address, :class_name => "Address", |
| 1934 | # :mapping => [%w(address_street street), %w(address_city city)] |
| 1935 | # end |
| 1936 | # Then: |
| 1937 | # { :address => Address.new("813 abc st.", "chicago") } |
| 1938 | # # => { :address_street => "813 abc st.", :address_city => "chicago" } |
| 1939 | def expand_hash_conditions_for_aggregates(attrs) |
| 1940 | expanded_attrs = {} |
| 1941 | attrs.each do |attr, value| |
| 1942 | unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil? |
| 1943 | mapping = aggregate_mapping(aggregation) |
| 1944 | mapping.each do |field_attr, aggregate_attr| |
| 1945 | if mapping.size == 1 && !value.respond_to?(aggregate_attr) |
| 1946 | expanded_attrs[field_attr] = value |
| 1947 | else |
| 1948 | expanded_attrs[field_attr] = value.send(aggregate_attr) |
| 1949 | end |
| 1950 | end |
| 1951 | else |
| 1952 | expanded_attrs[attr] = value |
| 1953 | end |
| 1954 | end |
| 1955 | expanded_attrs |
| 1956 | end |
| 1957 | |
| 1958 | # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause. |
| 1959 | # { :name => "foo'bar", :group_id => 4 } |
| 1960 | # # => "name='foo''bar' and group_id= 4" |
| 1961 | # { :status => nil, :group_id => [1,2,3] } |
| 1962 | # # => "status IS NULL and group_id IN (1,2,3)" |
| 1963 | # { :age => 13..18 } |
| 1964 | # # => "age BETWEEN 13 AND 18" |
| 1965 | # { 'other_records.id' => 7 } |
| 1966 | # # => "`other_records`.`id` = 7" |
| 1967 | # And for value objects on a composed_of relationship: |
| 1968 | # { :address => Address.new("123 abc st.", "chicago") } |
| 1969 | # # => "address_street='123 abc st.' and address_city='chicago'" |
| 1970 | def sanitize_sql_hash_for_conditions(attrs) |
| 1971 | attrs = expand_hash_conditions_for_aggregates(attrs) |
| 1972 | |
| 1973 | conditions = attrs.map do |attr, value| |
| 1974 | attr = attr.to_s |
| 1975 | |
| 1976 | # Extract table name from qualified attribute names. |
| 1977 | if attr.include?('.') |
| 1978 | table_name, attr = attr.split('.', 2) |
| 1979 | table_name = connection.quote_table_name(table_name) |
| 1980 | else |
| 1981 | table_name = quoted_table_name |
| 1982 | end |
| 1983 | |
| 1984 | "#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}" |
| 1985 | end.join(' AND ') |
| 1986 | |
| 1987 | replace_bind_variables(conditions, expand_range_bind_variables(attrs.values)) |
| 1988 | end |
| 1989 | alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions |
| 1990 | |
| 1991 | # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. |
| 1992 | # { :status => nil, :group_id => 1 } |
| 1993 | # # => "status = NULL , group_id = 1" |
| 1994 | def sanitize_sql_hash_for_assignment(attrs) |
| 1995 | attrs.map do |attr, value| |
| 1996 | "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}" |
| 1997 | end.join(', ') |
| 1998 | end |
| 1999 | |
| 2000 | # Accepts an array of conditions. The array has each value |
| 2001 | # sanitized and interpolated into the sql statement. |
| 2002 | # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" |
| 2003 | def sanitize_sql_array(ary) |
| 2004 | statement, *values = ary |
| 2005 | if values.first.is_a?(Hash) and statement =~ /:\w+/ |
| 2006 | replace_named_bind_variables(statement, values.first) |
| 2007 | elsif statement.include?('?') |
| 2008 | replace_bind_variables(statement, values) |
| 2009 | else |
| 2010 | statement % values.collect { |value| connection.quote_string(value.to_s) } |
| 2011 | end |
| 2012 | end |
| 2013 | |
| 2014 | alias_method :sanitize_conditions, :sanitize_sql |
| 2015 | |
| 2016 | def replace_bind_variables(statement, values) #:nodoc: |
| 2017 | raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) |
| 2018 | bound = values.dup |
| 2019 | statement.gsub('?') { quote_bound_value(bound.shift) } |
| 2020 | end |
| 2021 | |
| 2022 | def replace_named_bind_variables(statement, bind_vars) #:nodoc: |
| 2023 | statement.gsub(/:([a-zA-Z]\w*)/) do |
| 2024 | match = $1.to_sym |
| 2025 | if bind_vars.include?(match) |
| 2026 | quote_bound_value(bind_vars[match]) |
| 2027 | else |
| 2028 | raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" |
| 2029 | end |
| 2030 | end |
| 2031 | end |
| 2032 | |
| 2033 | def expand_range_bind_variables(bind_vars) #:nodoc: |
| 2034 | bind_vars.sum do |var| |
| 2035 | if var.is_a?(Range) |
| 2036 | [var.first, var.last] |
| 2037 | else |
| 2038 | [var] |
| 2039 | end |
| 2040 | end |
| 2041 | end |
| 2042 | |
| 2043 | def quote_bound_value(value) #:nodoc: |
| 2044 | if value.respond_to?(:map) && !value.is_a?(String) |
| 2045 | if value.respond_to?(:empty?) && value.empty? |
| 2046 | connection.quote(nil) |
| 2047 | else |
| 2048 | value.map { |v| connection.quote(v) }.join(',') |
| 2049 | end |
| 2050 | else |
| 2051 | connection.quote(value) |
| 2052 | end |
| 2053 | end |
| 2054 | |
| 2055 | def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc: |
| 2056 | unless expected == provided |
| 2057 | raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" |
| 2058 | end |
| 2059 | end |
| 2060 | |
| 2061 | VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, |
| 2062 | :order, :select, :readonly, :group, :from, :lock ] |
| 2063 | |
| 2064 | def validate_find_options(options) #:nodoc: |
| 2065 | options.assert_valid_keys(VALID_FIND_OPTIONS) |
| 2066 | end |
| 2067 | |
| 2068 | def set_readonly_option!(options) #:nodoc: |
| 2069 | # Inherit :readonly from finder scope if set. Otherwise, |
| 2070 | # if :joins is not blank then :readonly defaults to true. |
| 2071 | unless options.has_key?(:readonly) |
| 2072 | if scoped_readonly = scope(:find, :readonly) |
| 2073 | options[:readonly] = scoped_readonly |
| 2074 | elsif !options[:joins].blank? && !options[:select] |
| 2075 | options[:readonly] = true |
| 2076 | end |
| 2077 | end |
| 2078 | end |
| 2079 | |
| 2080 | def encode_quoted_value(value) #:nodoc: |
| 2081 | quoted_value = connection.quote(value) |
| 2082 | quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'") # (for ruby mode) " |
| 2083 | quoted_value |
| 2084 | end |
| 2085 | end |
| 2086 | |
| 2087 | public |
| 2088 | # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with |
| 2089 | # attributes but not yet saved (pass a hash with key names matching the associated table column names). |
| 2090 | # In both instances, valid attribute keys are determined by the column names of the associated table -- |
| 2091 | # hence you can't have attributes that aren't part of the table columns. |
| 2092 | def initialize(attributes = nil) |
| 2093 | @attributes = attributes_from_column_definition |
| 2094 | @attributes_cache = {} |
| 2095 | @new_record = true |
| 2096 | ensure_proper_type |
| 2097 | self.attributes = attributes unless attributes.nil? |
| 2098 | self.class.send(:scope, :create).each { |att,value| self.send("#{att}=", value) } if self.class.send(:scoped?, :create) |
| 2099 | result = yield self if block_given? |
| 2100 | callback(:after_initialize) if respond_to_without_attributes?(:after_initialize) |
| 2101 | result |
| 2102 | end |
| 2103 | |
| 2104 | # A model instance's primary key is always available as model.id |
| 2105 | # whether you name it the default 'id' or set it to something else. |
| 2106 | def id |
| 2107 | attr_name = self.class.primary_key |
| 2108 | column = column_for_attribute(attr_name) |
| 2109 | |
| 2110 | self.class.send(:define_read_method, :id, attr_name, column) |
| 2111 | # now that the method exists, call it |
| 2112 | self.send attr_name.to_sym |
| 2113 | |
| 2114 | end |
| 2115 | |
| 2116 | # Enables Active Record objects to be used as URL parameters in Action Pack automatically. |
| 2117 | def to_param |
| 2118 | # We can't use alias_method here, because method 'id' optimizes itself on the fly. |
| 2119 | (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes |
| 2120 | end |
| 2121 | |
| 2122 | # Returns a cache key that can be used to identify this record. Examples: |
| 2123 | # |
| 2124 | # Product.new.cache_key # => "products/new" |
| 2125 | # Product.find(5).cache_key # => "products/5" (updated_at not available) |
| 2126 | # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available) |
| 2127 | def cache_key |
| 2128 | case |
| 2129 | when new_record? |
| 2130 | "#{self.class.name.tableize}/new" |
| 2131 | when self[:updated_at] |
| 2132 | "#{self.class.name.tableize}/#{id}-#{updated_at.to_s(:number)}" |
| 2133 | else |
| 2134 | "#{self.class.name.tableize}/#{id}" |
| 2135 | end |
| 2136 | end |
| 2137 | |
| 2138 | def id_before_type_cast #:nodoc: |
| 2139 | read_attribute_before_type_cast(self.class.primary_key) |
| 2140 | end |
| 2141 | |
| 2142 | def quoted_id #:nodoc: |
| 2143 | quote_value(id, column_for_attribute(self.class.primary_key)) |
| 2144 | end |
| 2145 | |
| 2146 | # Sets the primary ID. |
| 2147 | def id=(value) |
| 2148 | write_attribute(self.class.primary_key, value) |
| 2149 | end |
| 2150 | |
| 2151 | # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet. |
| 2152 | def new_record? |
| 2153 | defined?(@new_record) && @new_record |
| 2154 | end |
| 2155 | |
| 2156 | # * No record exists: Creates a new record with values matching those of the object attributes. |
| 2157 | # * A record does exist: Updates the record with values matching those of the object attributes. |
| 2158 | # |
| 2159 | # Note: If your model specifies any validations then the method declaration dynamically |
| 2160 | # changes to: |
| 2161 | # save(perform_validation=true) |
| 2162 | # Calling save(false) saves the model without running validations. |
| 2163 | # See ActiveRecord::Validations for more information. |
| 2164 | def save |
| 2165 | create_or_update |
| 2166 | end |
| 2167 | |
| 2168 | # Attempts to save the record, but instead of just returning false if it couldn't happen, it raises a |
| 2169 | # RecordNotSaved exception |
| 2170 | def save! |
| 2171 | create_or_update || raise(RecordNotSaved) |
| 2172 | end |
| 2173 | |
| 2174 | # Deletes the record in the database and freezes this instance to reflect that no changes should |
| 2175 | # be made (since they can't be persisted). |
| 2176 | def destroy |
| 2177 | unless new_record? |
| 2178 | connection.delete <<-end_sql, "#{self.class.name} Destroy" |
| 2179 | DELETE FROM #{self.class.quoted_table_name} |
| 2180 | WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id} |
| 2181 | end_sql |
| 2182 | end |
| 2183 | |
| 2184 | freeze |
| 2185 | end |
| 2186 | |
| 2187 | # Returns a clone of the record that hasn't been assigned an id yet and |
| 2188 | # is treated as a new record. Note that this is a "shallow" clone: |
| 2189 | # it copies the object's attributes only, not its associations. |
| 2190 | # The extent of a "deep" clone is application-specific and is therefore |
| 2191 | # left to the application to implement according to its need. |
| 2192 | def clone |
| 2193 | attrs = clone_attributes(:read_attribute_before_type_cast) |
| 2194 | attrs.delete(self.class.primary_key) |
| 2195 | record = self.class.new |
| 2196 | record.send :instance_variable_set, '@attributes', attrs |
| 2197 | record |
| 2198 | end |
| 2199 | |
| 2200 | # Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to |
| 2201 | # single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record |
| 2202 | # identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company) |
| 2203 | # to render that instance using the companies/company partial instead of clients/client. |
| 2204 | # |
| 2205 | # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either |
| 2206 | # instance will affect the other. |
| 2207 | def becomes(klass) |
| 2208 | returning klass.new do |became| |
| 2209 | became.instance_variable_set("@attributes", @attributes) |
| 2210 | became.instance_variable_set("@attributes_cache", @attributes_cache) |
| 2211 | became.instance_variable_set("@new_record", new_record?) |
| 2212 | end |
| 2213 | end |
| 2214 | |
| 2215 | # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. |
| 2216 | # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method |
| 2217 | # aren't subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid. |
| 2218 | def update_attribute(name, value) |
| 2219 | send(name.to_s + '=', value) |
| 2220 | save |
| 2221 | end |
| 2222 | |
| 2223 | # Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will |
| 2224 | # fail and false will be returned. |
| 2225 | def update_attributes(attributes) |
| 2226 | self.attributes = attributes |
| 2227 | save |
| 2228 | end |
| 2229 | |
| 2230 | # Updates an object just like Base.update_attributes but calls save! instead of save so an exception is raised if the record is invalid. |
| 2231 | def update_attributes!(attributes) |
| 2232 | self.attributes = attributes |
| 2233 | save! |
| 2234 | end |
| 2235 | |
| 2236 | # Initializes the +attribute+ to zero if nil and adds the value passed as +by+ (default is one). Only makes sense for number-based attributes. Returns self. |
| 2237 | def increment(attribute, by = 1) |
| 2238 | self[attribute] ||= 0 |
| 2239 | self[attribute] += by |
| 2240 | self |
| 2241 | end |
| 2242 | |
| 2243 | # Increments the +attribute+ and saves the record. |
| 2244 | # Note: Updates made with this method aren't subjected to validation checks |
| 2245 | def increment!(attribute, by = 1) |
| 2246 | increment(attribute, by).update_attribute(attribute, self[attribute]) |
| 2247 | end |
| 2248 | |
| 2249 | # Initializes the +attribute+ to zero if nil and subtracts the value passed as +by+ (default is one). Only makes sense for number-based attributes. Returns self. |
| 2250 | def decrement(attribute, by = 1) |
| 2251 | self[attribute] ||= 0 |
| 2252 | self[attribute] -= by |
| 2253 | self |
| 2254 | end |
| 2255 | |
| 2256 | # Decrements the +attribute+ and saves the record. |
| 2257 | # Note: Updates made with this method aren't subjected to validation checks |
| 2258 | def decrement!(attribute, by = 1) |
| 2259 | decrement(attribute, by).update_attribute(attribute, self[attribute]) |
| 2260 | end |
| 2261 | |
| 2262 | # Turns an +attribute+ that's currently true into false and vice versa. Returns self. |
| 2263 | def toggle(attribute) |
| 2264 | self[attribute] = !send("#{attribute}?") |
| 2265 | self |
| 2266 | end |
| 2267 | |
| 2268 | # Toggles the +attribute+ and saves the record. |
| 2269 | # Note: Updates made with this method aren't subjected to validation checks |
| 2270 | def toggle!(attribute) |
| 2271 | toggle(attribute).update_attribute(attribute, self[attribute]) |
| 2272 | end |
| 2273 | |
| 2274 | # Reloads the attributes of this object from the database. |
| 2275 | # The optional options argument is passed to find when reloading so you |
| 2276 | # may do e.g. record.reload(:lock => true) to reload the same record with |
| 2277 | # an exclusive row lock. |
| 2278 | def reload(options = nil) |
| 2279 | clear_aggregation_cache |
| 2280 | clear_association_cache |
| 2281 | @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes')) |
| 2282 | @attributes_cache = {} |
| 2283 | self |
| 2284 | end |
| 2285 | |
| 2286 | # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example, |
| 2287 | # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). |
| 2288 | # (Alias for the protected read_attribute method). |
| 2289 | def [](attr_name) |
| 2290 | read_attribute(attr_name) |
| 2291 | end |
| 2292 | |
| 2293 | # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. |
| 2294 | # (Alias for the protected write_attribute method). |
| 2295 | def []=(attr_name, value) |
| 2296 | write_attribute(attr_name, value) |
| 2297 | end |
| 2298 | |
| 2299 | # Allows you to set all the attributes at once by passing in a hash with keys |
| 2300 | # matching the attribute names (which again matches the column names). Sensitive attributes can be protected |
| 2301 | # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively |
| 2302 | # specify which attributes *can* be accessed with the +attr_accessible+ macro. Then all the |
| 2303 | # attributes not included in that won't be allowed to be mass-assigned. |
| 2304 | def attributes=(new_attributes, guard_protected_attributes = true) |
| 2305 | return if new_attributes.nil? |
| 2306 | attributes = new_attributes.dup |
| 2307 | attributes.stringify_keys! |
| 2308 | |
| 2309 | multi_parameter_attributes = [] |
| 2310 | attributes = remove_attributes_protected_from_mass_assignment(attributes) if guard_protected_attributes |
| 2311 | |
| 2312 | attributes.each do |k, v| |
| 2313 | k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v) |
| 2314 | end |
| 2315 | |
| 2316 | assign_multiparameter_attributes(multi_parameter_attributes) |
| 2317 | end |
| 2318 | |
| 2319 | |
| 2320 | # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. |
| 2321 | def attributes(options = nil) |
| 2322 | self.attribute_names.inject({}) do |attrs, name| |
| 2323 | attrs[name] = read_attribute(name) |
| 2324 | attrs |
| 2325 | end |
| 2326 | end |
| 2327 | |
| 2328 | # Returns a hash of attributes before typecasting and deserialization. |
| 2329 | def attributes_before_type_cast |
| 2330 | self.attribute_names.inject({}) do |attrs, name| |
| 2331 | attrs[name] = read_attribute_before_type_cast(name) |
| 2332 | attrs |
| 2333 | end |
| 2334 | end |
| 2335 | |
| 2336 | # Format attributes nicely for inspect. |
| 2337 | def attribute_for_inspect(attr_name) |
| 2338 | value = read_attribute(attr_name) |
| 2339 | |
| 2340 | if value.is_a?(String) && value.length > 50 |
| 2341 | "#{value[0..50]}...".inspect |
| 2342 | elsif value.is_a?(Date) || value.is_a?(Time) |
| 2343 | %("#{value.to_s(:db)}") |
| 2344 | else |
| 2345 | value.inspect |
| 2346 | end |
| 2347 | end |
| 2348 | |
| 2349 | # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither |
| 2350 | # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings). |
| 2351 | def attribute_present?(attribute) |
| 2352 | value = read_attribute(attribute) |
| 2353 | !value.blank? |
| 2354 | end |
| 2355 | |
| 2356 | # Returns true if the given attribute is in the attributes hash |
| 2357 | def has_attribute?(attr_name) |
| 2358 | @attributes.has_key?(attr_name.to_s) |
| 2359 | end |
| 2360 | |
| 2361 | # Returns an array of names for the attributes available on this object sorted alphabetically. |
| 2362 | def attribute_names |
| 2363 | @attributes.keys.sort |
| 2364 | end |
| 2365 | |
| 2366 | # Returns the column object for the named attribute. |
| 2367 | def column_for_attribute(name) |
| 2368 | self.class.columns_hash[name.to_s] |
| 2369 | end |
| 2370 | |
| 2371 | # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id. |
| 2372 | def ==(comparison_object) |
| 2373 | comparison_object.equal?(self) || |
| 2374 | (comparison_object.instance_of?(self.class) && |
| 2375 | comparison_object.id == id && |
| 2376 | !comparison_object.new_record?) |
| 2377 | end |
| 2378 | |
| 2379 | # Delegates to == |
| 2380 | def eql?(comparison_object) |
| 2381 | self == (comparison_object) |
| 2382 | end |
| 2383 | |
| 2384 | # Delegates to id in order to allow two records of the same type and id to work with something like: |
| 2385 | # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] |
| 2386 | def hash |
| 2387 | id.hash |
| 2388 | end |
| 2389 | |
| 2390 | # Freeze the attributes hash such that associations are still accessible, even on destroyed records. |
| 2391 | def freeze |
| 2392 | @attributes.freeze; self |
| 2393 | end |
| 2394 | |
| 2395 | # Returns +true+ if the attributes hash has been frozen. |
| 2396 | def frozen? |
| 2397 | @attributes.frozen? |
| 2398 | end |
| 2399 | |
| 2400 | # Returns +true+ if the record is read only. Records loaded through joins with piggy-back |
| 2401 | # attributes will be marked as read only since they cannot be saved. |
| 2402 | def readonly? |
| 2403 | defined?(@readonly) && @readonly == |