# File lib/active_record/relation.rb, line 311
311: def primary_key
312: @primary_key ||= table[@klass.primary_key]
313: end
Object
# File lib/active_record/relation.rb, line 20
20: def initialize(klass, table)
21: @klass, @table = klass, table
22:
23: @implicit_readonly = nil
24: @loaded = 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: end
# File lib/active_record/relation.rb, line 339
339: def ==(other)
340: case other
341: when Relation
342: other.to_sql == to_sql
343: when Array
344: to_a == other.to_a
345: end
346: end
# File lib/active_record/relation.rb, line 91
91: def any?
92: if block_given?
93: to_a.any? { |*block_args| yield(*block_args) }
94: else
95: !empty?
96: end
97: end
# File lib/active_record/relation.rb, line 79
79: def as_json(options = nil) to_a end
# File lib/active_record/relation.rb, line 41
41: def create(*args, &block)
42: scoping { @klass.create(*args, &block) }
43: end
# File lib/active_record/relation.rb, line 45
45: def create!(*args, &block)
46: scoping { @klass.create!(*args, &block) }
47: 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 294
294: def delete(id_or_array)
295: where(@klass.primary_key => id_or_array).delete_all
296: 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'])
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 270
270: def delete_all(conditions = nil)
271: conditions ? where(conditions).delete_all : arel.delete.tap { reset }
272: 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 244
244: def destroy(id)
245: if id.is_a?(Array)
246: id.map { |one_id| destroy(one_id) }
247: else
248: find(id).destroy
249: end
250: 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")
# File lib/active_record/relation.rb, line 217
217: def destroy_all(conditions = nil)
218: if conditions
219: where(conditions).destroy_all
220: else
221: to_a.each {|object| object.destroy }.tap { reset }
222: end
223: end
# File lib/active_record/relation.rb, line 335
335: def eager_loading?
336: @should_eager_load ||= (@eager_load_values.any? || (@includes_values.any? && references_eager_loaded_tables?))
337: end
Returns true if there are no records.
# File lib/active_record/relation.rb, line 87
87: def empty?
88: loaded? ? @records.empty? : count.zero?
89: end
# File lib/active_record/relation.rb, line 35
35: def initialize_copy(other)
36: reset
37: end
# File lib/active_record/relation.rb, line 348
348: def inspect
349: to_a.inspect
350: end
# File lib/active_record/relation.rb, line 99
99: def many?
100: if block_given?
101: to_a.many? { |*block_args| yield(*block_args) }
102: else
103: @limit_value ? to_a.many? : size > 1
104: end
105: end
# File lib/active_record/relation.rb, line 31
31: def new(*args, &block)
32: scoping { @klass.new(*args, &block) }
33: end
# File lib/active_record/relation.rb, line 311
311: def primary_key
312: @primary_key ||= table[@klass.primary_key]
313: end
# File lib/active_record/relation.rb, line 298
298: def reload
299: reset
300: to_a # force reload
301: self
302: end
# File lib/active_record/relation.rb, line 304
304: def reset
305: @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
306: @should_eager_load = @join_dependency = nil
307: @records = []
308: self
309: end
# File lib/active_record/relation.rb, line 49
49: def respond_to?(method, include_private = false)
50: return true if arel.respond_to?(method, include_private) || Array.method_defined?(method) || @klass.respond_to?(method, include_private)
51:
52: if match = DynamicFinderMatch.match(method)
53: return true if @klass.send(:all_attributes_exists?, match.attribute_names)
54: elsif match = DynamicScopeMatch.match(method)
55: return true if @klass.send(:all_attributes_exists?, match.attribute_names)
56: else
57: super
58: end
59: end
# File lib/active_record/relation.rb, line 329
329: def scope_for_create
330: @scope_for_create ||= begin
331: @create_with_value || where_values_hash
332: end
333: 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 117
117: def scoping
118: @klass.scoped_methods << self
119: begin
120: yield
121: ensure
122: @klass.scoped_methods.pop
123: end
124: end
Returns size of the records.
# File lib/active_record/relation.rb, line 82
82: def size
83: loaded? ? @records.length : count
84: end
# File lib/active_record/relation.rb, line 61
61: def to_a
62: return @records if loaded?
63:
64: @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql)
65:
66: preload = @preload_values
67: preload += @includes_values unless eager_loading?
68: preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
69:
70: # @readonly_value is true only if set explicitly. @implicit_readonly is true if there
71: # are JOINS and no explicit SELECT.
72: readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
73: @records.each { |record| record.readonly! } if readonly
74:
75: @loaded = true
76: @records
77: end
# File lib/active_record/relation.rb, line 315
315: def to_sql
316: @to_sql ||= arel.to_sql
317: 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 180
180: def update(id, attributes)
181: if id.is_a?(Array)
182: idx = 1
183: id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
184: else
185: object = find(id)
186: object.update_attributes(attributes)
187: object
188: end
189: 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
# File lib/active_record/relation.rb, line 151
151: def update_all(updates, conditions = nil, options = {})
152: if conditions || options.present?
153: where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
154: else
155: # Apply limit and order only if they're both present
156: if @limit_value.present? == @order_values.present?
157: arel.update(Arel::SqlLiteral.new(@klass.send(:sanitize_sql_for_assignment, updates)))
158: else
159: except(:limit, :order).update_all(updates)
160: end
161: end
162: end
# File lib/active_record/relation.rb, line 319
319: def where_values_hash
320: Hash[@where_values.find_all { |w|
321: w.respond_to?(:operator) && w.operator == :==
322: }.map { |where|
323: [where.operand1.name,
324: where.operand2.respond_to?(:value) ?
325: where.operand2.value : where.operand2]
326: }]
327: end
# File lib/active_record/relation.rb, line 354
354: def method_missing(method, *args, &block)
355: if Array.method_defined?(method)
356: to_a.send(method, *args, &block)
357: elsif @klass.scopes[method]
358: merge(@klass.send(method, *args, &block))
359: elsif @klass.respond_to?(method)
360: scoping { @klass.send(method, *args, &block) }
361: elsif arel.respond_to?(method)
362: arel.send(method, *args, &block)
363: elsif match = DynamicFinderMatch.match(method)
364: attributes = match.attribute_names
365: super unless @klass.send(:all_attributes_exists?, attributes)
366:
367: if match.finder?
368: find_by_attributes(match, attributes, *args)
369: elsif match.instantiator?
370: find_or_instantiator_by_attributes(match, attributes, *args, &block)
371: end
372: else
373: super
374: end
375: end
# File lib/active_record/relation.rb, line 379
379: def references_eager_loaded_tables?
380: # always convert table names to downcase as in Oracle quoted table names are in uppercase
381: joined_tables = (tables_in_string(arel.joins(arel)) + [table.name, table.table_alias]).compact.map{ |t| t.downcase }.uniq
382: (tables_in_string(to_sql) - joined_tables).any?
383: end
# File lib/active_record/relation.rb, line 385
385: def tables_in_string(string)
386: return [] if string.blank?
387: # always convert table names to downcase as in Oracle quoted table names are in uppercase
388: # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
389: string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
390: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.