Object
# File lib/active_record/relation.rb, line 19 19: def initialize(klass, table) 20: @klass, @table = klass, table 21: 22: @implicit_readonly = nil 23: @loaded = false 24: @default_scoped = false 25: 26: SINGLE_VALUE_METHODS.each {|v| instance_variable_set(:"@#{v}_value", nil)} 27: (ASSOCIATION_METHODS + MULTI_VALUE_METHODS).each {|v| instance_variable_set(:"@#{v}_values", [])} 28: @extensions = [] 29: @create_with_value = {} 30: end
# File lib/active_record/relation.rb, line 488 488: def ==(other) 489: case other 490: when Relation 491: other.to_sql == to_sql 492: when Array 493: to_a == other 494: end 495: end
# File lib/active_record/relation.rb, line 214 214: def any? 215: if block_given? 216: to_a.any? { |*block_args| yield(*block_args) } 217: else 218: !empty? 219: end 220: end
# File lib/active_record/relation.rb, line 86 86: def create(*args, &block) 87: scoping { @klass.create(*args, &block) } 88: end
# File lib/active_record/relation.rb, line 90 90: def create!(*args, &block) 91: scoping { @klass.create!(*args, &block) } 92: end
Deletes the row with a primary key matching the id argument, using a SQL DELETE statement, and returns the number of rows deleted. Active Record objects are not instantiated, so the object’s callbacks are not executed, including any :dependent association options or Observer methods.
You can delete multiple rows at once by passing an Array of ids.
Note: Although it is often much faster than the alternative, #, skipping callbacks might bypass business logic in your application that ensures referential integrity or performs other essential jobs.
# Delete a single row Todo.delete(1) # Delete multiple rows Todo.delete([2,3,4])
# File lib/active_record/relation.rb, line 440 440: def delete(id_or_array) 441: IdentityMap.remove_by_id(self.symbolized_base_class, id_or_array) if IdentityMap.enabled? 442: where(primary_key => id_or_array).delete_all 443: end
Deletes the records matching conditions without instantiating the records first, and hence not calling the destroy method nor invoking callbacks. This is a single SQL DELETE statement that goes straight to the database, much more efficient than destroy_all. Be careful with relations though, in particular :dependent rules defined on associations are not honored. Returns the number of rows affected.
conditions - Conditions are specified the same way as with find method.
Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')") Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else']) Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent associations or call your before_* or after_destroy callbacks, use the destroy_all method instead.
# File lib/active_record/relation.rb, line 405 405: def delete_all(conditions = nil) 406: raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value 407: 408: IdentityMap.repository[symbolized_base_class] = {} if IdentityMap.enabled? 409: if conditions 410: where(conditions).delete_all 411: else 412: statement = arel.compile_delete 413: affected = @klass.connection.delete(statement, 'SQL', bind_values) 414: 415: reset 416: affected 417: end 418: end
Destroy an object (or multiple objects) that has the given id, the object is instantiated first, therefore all callbacks and filters are fired off before the object is deleted. This method is less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
This essentially finds the object (or multiple objects) with the given id, creates a new object from the attributes, and then calls destroy on it.
id - Can be either an Integer or an Array of Integers.
# Destroy a single object Todo.destroy(1) # Destroy multiple objects todos = [1,2,3] Todo.destroy(todos)
# File lib/active_record/relation.rb, line 378 378: def destroy(id) 379: if id.is_a?(Array) 380: id.map { |one_id| destroy(one_id) } 381: else 382: find(id).destroy 383: end 384: end
Destroys the records matching conditions by instantiating each record and calling its destroy method. Each object’s callbacks are executed (including :dependent association options and before_destroy/after_destroy Observer methods). Returns the collection of objects that were destroyed; each will be frozen, to reflect that no changes should be made (since they can’t be persisted).
Note: Instantiation, callback execution, and deletion of each record can be time consuming when you’re removing many records at once. It generates at least one SQL DELETE query per record (or possibly more, to enforce your callbacks). If you want to delete many rows quickly, without concern for their associations or callbacks, use delete_all instead.
conditions - A string, array, or hash that specifies which records to destroy. If omitted, all records are destroyed. See the Conditions section in the introduction to ActiveRecord::Base for more information.
Person.destroy_all("last_login < '2004-04-04'") Person.destroy_all(:status => "inactive") Person.where(:age => 0..18).destroy_all
# File lib/active_record/relation.rb, line 351 351: def destroy_all(conditions = nil) 352: if conditions 353: where(conditions).destroy_all 354: else 355: to_a.each {|object| object.destroy }.tap { reset } 356: end 357: end
# File lib/active_record/relation.rb, line 474 474: def eager_loading? 475: @should_eager_load ||= 476: @eager_load_values.any? || 477: @includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?) 478: end
Returns true if there are no records.
# File lib/active_record/relation.rb, line 207 207: def empty? 208: return @records.empty? if loaded? 209: 210: c = count 211: c.respond_to?(:zero?) ? c.zero? : c.empty? 212: end
Runs EXPLAIN on the query or queries triggered by this relation and returns the result as a string. The string is formatted imitating the ones printed by the database shell.
Note that this method actually runs the queries, since the results of some are needed by the next ones when eager loading is going on.
Please see further details in the Active Record Query Interface guide.
# File lib/active_record/relation.rb, line 145 145: def explain 146: _, queries = collecting_queries_for_explain { exec_queries } 147: exec_explain(queries) 148: end
Tries to load the first record; if it fails, then create is called with the same arguments as this method.
Expects arguments in the same format as Base.create.
# Find the first user named Penélope or create a new one. User.where(:first_name => 'Penélope').first_or_create # => <User id: 1, first_name: 'Penélope', last_name: nil> # Find the first user named Penélope or create a new one. # We already have one so the existing record will be returned. User.where(:first_name => 'Penélope').first_or_create # => <User id: 1, first_name: 'Penélope', last_name: nil> # Find the first user named Scarlett or create a new one with a particular last name. User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson') # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'> # Find the first user named Scarlett or create a new one with a different last name. # We already have one so the existing record will be returned. User.where(:first_name => 'Scarlett').first_or_create do |user| user.last_name = "O'Hara" end # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
# File lib/active_record/relation.rb, line 118 118: def first_or_create(attributes = nil, options = {}, &block) 119: first || create(attributes, options, &block) 120: end
Like first_or_create but calls create! so an exception is raised if the created record is invalid.
Expects arguments in the same format as Base.create!.
# File lib/active_record/relation.rb, line 125 125: def first_or_create!(attributes = nil, options = {}, &block) 126: first || create!(attributes, options, &block) 127: end
Like first_or_create but calls new instead of create.
Expects arguments in the same format as Base.new.
# File lib/active_record/relation.rb, line 132 132: def first_or_initialize(attributes = nil, options = {}, &block) 133: first || new(attributes, options, &block) 134: end
# File lib/active_record/relation.rb, line 79 79: def initialize_copy(other) 80: @bind_values = @bind_values.dup 81: reset 82: end
# File lib/active_record/relation.rb, line 32 32: def insert(values) 33: primary_key_value = nil 34: 35: if primary_key && Hash === values 36: primary_key_value = values[values.keys.find { |k| 37: k.name == primary_key 38: }] 39: 40: if !primary_key_value && connection.prefetch_primary_key?(klass.table_name) 41: primary_key_value = connection.next_sequence_value(klass.sequence_name) 42: values[klass.arel_table[klass.primary_key]] = primary_key_value 43: end 44: end 45: 46: im = arel.create_insert 47: im.into @table 48: 49: conn = @klass.connection 50: 51: substitutes = values.sort_by { |arel_attr,_| arel_attr.name } 52: binds = substitutes.map do |arel_attr, value| 53: [@klass.columns_hash[arel_attr.name], value] 54: end 55: 56: substitutes.each_with_index do |tuple, i| 57: tuple[1] = conn.substitute_at(binds[i][0], i) 58: end 59: 60: if values.empty? # empty insert 61: im.values = Arel.sql(connection.empty_insert_statement_value) 62: else 63: im.insert substitutes 64: end 65: 66: conn.insert( 67: im, 68: 'SQL', 69: primary_key, 70: primary_key_value, 71: nil, 72: binds) 73: end
# File lib/active_record/relation.rb, line 497 497: def inspect 498: to_a.inspect 499: end
Joins that are also marked for preloading. In which case we should just eager load them. Note that this is a naive implementation because we could have strings and symbols which represent the same association, but that aren’t matched by this. Also, we could have nested hashes which partially match, e.g. { :a => :b } & { :a => [:b, :c] }
# File lib/active_record/relation.rb, line 484 484: def joined_includes_values 485: @includes_values & @joins_values 486: end
# File lib/active_record/relation.rb, line 222 222: def many? 223: if block_given? 224: to_a.many? { |*block_args| yield(*block_args) } 225: else 226: @limit_value ? to_a.many? : size > 1 227: end 228: end
# File lib/active_record/relation.rb, line 75 75: def new(*args, &block) 76: scoping { @klass.new(*args, &block) } 77: end
# File lib/active_record/relation.rb, line 445 445: def reload 446: reset 447: to_a # force reload 448: self 449: end
# File lib/active_record/relation.rb, line 451 451: def reset 452: @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil 453: @should_eager_load = @join_dependency = nil 454: @records = [] 455: self 456: end
# File lib/active_record/relation.rb, line 470 470: def scope_for_create 471: @scope_for_create ||= where_values_hash.merge(create_with_value) 472: end
Scope all queries to the current scope.
Comment.where(:post_id => 1).scoping do Comment.first # SELECT * FROM comments WHERE post_id = 1 end
Please check unscoped if you want to remove all previous scopes (including the default_scope) during the execution of a block.
# File lib/active_record/relation.rb, line 240 240: def scoping 241: @klass.with_scope(self, :overwrite) { yield } 242: end
Returns size of the records.
# File lib/active_record/relation.rb, line 202 202: def size 203: loaded? ? @records.length : count 204: end
# File lib/active_record/relation.rb, line 150 150: def to_a 151: # We monitor here the entire execution rather than individual SELECTs 152: # because from the point of view of the user fetching the records of a 153: # relation is a single unit of work. You want to know if this call takes 154: # too long, not if the individual queries take too long. 155: # 156: # It could be the case that none of the queries involved surpass the 157: # threshold, and at the same time the sum of them all does. The user 158: # should get a query plan logged in that case. 159: logging_query_plan do 160: exec_queries 161: end 162: end
# File lib/active_record/relation.rb, line 458 458: def to_sql 459: @to_sql ||= klass.connection.to_sql(arel, @bind_values.dup) 460: end
Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.
id - This should be the id or an array of ids to be updated.
attributes - This should be a hash of attributes or an array of hashes.
# Updates one record Person.update(15, :user_name => 'Samuel', :group => 'expert') # Updates multiple records people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } } Person.update(people.keys, people.values)
# File lib/active_record/relation.rb, line 314 314: def update(id, attributes) 315: if id.is_a?(Array) 316: id.each.with_index.map {|one_id, idx| update(one_id, attributes[idx])} 317: else 318: object = find(id) 319: object.update_attributes(attributes) 320: object 321: end 322: end
Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations.
updates - A string, array, or hash representing the SET part of an SQL statement.
conditions - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro.
options - Additional options are :limit and :order, see the examples for usage.
# Update all customers with the given attributes Customer.update_all :wants_email => true # Update all books with 'Rails' in their title Book.update_all "author = 'David'", "title LIKE '%Rails%'" # Update all avatars migrated more than a week ago Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago] # Update all books that match conditions, but limit it to 5 ordered by date Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5 # Conditions from the current relation also works Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David') # The same idea applies to limit and order Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
# File lib/active_record/relation.rb, line 275 275: def update_all(updates, conditions = nil, options = {}) 276: IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled? 277: if conditions || options.present? 278: where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates) 279: else 280: stmt = Arel::UpdateManager.new(arel.engine) 281: 282: stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) 283: stmt.table(table) 284: stmt.key = table[primary_key] 285: 286: if joins_values.any? 287: @klass.connection.join_to_update(stmt, arel) 288: else 289: stmt.take(arel.limit) 290: stmt.order(*arel.orders) 291: stmt.wheres = arel.constraints 292: end 293: 294: @klass.connection.update stmt, 'SQL', bind_values 295: end 296: end
# File lib/active_record/relation.rb, line 462 462: def where_values_hash 463: equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node| 464: node.left.relation.name == table_name 465: } 466: 467: Hash[equalities.map { |where| [where.left.name, where.right] }] 468: end
# File lib/active_record/relation.rb, line 164 164: def exec_queries 165: return @records if loaded? 166: 167: default_scoped = with_default_scope 168: 169: if default_scoped.equal?(self) 170: @records = if @readonly_value.nil? && !@klass.locking_enabled? 171: eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values) 172: else 173: IdentityMap.without do 174: eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values) 175: end 176: end 177: 178: preload = @preload_values 179: preload += @includes_values unless eager_loading? 180: preload.each do |associations| 181: ActiveRecord::Associations::Preloader.new(@records, associations).run 182: end 183: 184: # @readonly_value is true only if set explicitly. @implicit_readonly is true if there 185: # are JOINS and no explicit SELECT. 186: readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value 187: @records.each { |record| record.readonly! } if readonly 188: else 189: @records = default_scoped.to_a 190: end 191: 192: @loaded = true 193: @records 194: end
# File lib/active_record/relation.rb, line 513 513: def references_eager_loaded_tables? 514: joined_tables = arel.join_sources.map do |join| 515: if join.is_a?(Arel::Nodes::StringJoin) 516: tables_in_string(join.left) 517: else 518: [join.left.table_name, join.left.table_alias] 519: end 520: end 521: 522: joined_tables += [table.name, table.table_alias] 523: 524: # always convert table names to downcase as in Oracle quoted table names are in uppercase 525: joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq 526: 527: (tables_in_string(to_sql) - joined_tables).any? 528: end
# File lib/active_record/relation.rb, line 530 530: def tables_in_string(string) 531: return [] if string.blank? 532: # always convert table names to downcase as in Oracle quoted table names are in uppercase 533: # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries 534: string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_'] 535: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.