# File lib/active_record/relation.rb, line 313 313: def primary_key 314: @primary_key ||= table[@klass.primary_key] 315: 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 346 346: def ==(other) 347: case other 348: when Relation 349: other.to_sql == to_sql 350: when Array 351: to_a == other.to_a 352: end 353: end
# File lib/active_record/relation.rb, line 93 93: def any? 94: if block_given? 95: to_a.any? { |*block_args| yield(*block_args) } 96: else 97: !empty? 98: end 99: 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 296 296: def delete(id_or_array) 297: where(@klass.primary_key => id_or_array).delete_all 298: 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 272 272: def delete_all(conditions = nil) 273: conditions ? where(conditions).delete_all : arel.delete.tap { reset } 274: 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 246 246: def destroy(id) 247: if id.is_a?(Array) 248: id.map { |one_id| destroy(one_id) } 249: else 250: find(id).destroy 251: end 252: 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 219 219: def destroy_all(conditions = nil) 220: if conditions 221: where(conditions).destroy_all 222: else 223: to_a.each {|object| object.destroy }.tap { reset } 224: end 225: end
# File lib/active_record/relation.rb, line 342 342: def eager_loading? 343: @should_eager_load ||= (@eager_load_values.any? || (@includes_values.any? && references_eager_loaded_tables?)) 344: end
Returns true if there are no records.
# File lib/active_record/relation.rb, line 89 89: def empty? 90: loaded? ? @records.empty? : count.zero? 91: 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 355 355: def inspect 356: to_a.inspect 357: end
# File lib/active_record/relation.rb, line 101 101: def many? 102: if block_given? 103: to_a.many? { |*block_args| yield(*block_args) } 104: else 105: @limit_value ? to_a.many? : size > 1 106: end 107: 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 313 313: def primary_key 314: @primary_key ||= table[@klass.primary_key] 315: end
# File lib/active_record/relation.rb, line 300 300: def reload 301: reset 302: to_a # force reload 303: self 304: end
# File lib/active_record/relation.rb, line 306 306: def reset 307: @first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil 308: @should_eager_load = @join_dependency = nil 309: @records = [] 310: self 311: 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 332 332: def scope_for_create 333: @scope_for_create ||= begin 334: if @create_with_value 335: @create_with_value.reverse_merge(where_values_hash) 336: else 337: where_values_hash 338: end 339: end 340: 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 119 119: def scoping 120: @klass.scoped_methods << self 121: begin 122: yield 123: ensure 124: @klass.scoped_methods.pop 125: end 126: end
Returns size of the records.
# File lib/active_record/relation.rb, line 84 84: def size 85: loaded? ? @records.length : count 86: 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 317 317: def to_sql 318: @to_sql ||= arel.to_sql 319: 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 182 182: def update(id, attributes) 183: if id.is_a?(Array) 184: idx = 1 185: id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) } 186: else 187: object = find(id) 188: object.update_attributes(attributes) 189: object 190: end 191: 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 153 153: def update_all(updates, conditions = nil, options = {}) 154: if conditions || options.present? 155: where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates) 156: else 157: # Apply limit and order only if they're both present 158: if @limit_value.present? == @order_values.present? 159: arel.update(Arel::SqlLiteral.new(@klass.send(:sanitize_sql_for_assignment, updates))) 160: else 161: except(:limit, :order).update_all(updates) 162: end 163: end 164: end
# File lib/active_record/relation.rb, line 321 321: def where_values_hash 322: Hash[@where_values.find_all { |w| 323: w.respond_to?(:operator) && w.operator == :== && w.left.relation.name == table_name 324: }.map { |where| 325: [ 326: where.left.name, 327: where.right.respond_to?(:value) ? where.right.value : where.right 328: ] 329: }] 330: end
# File lib/active_record/relation.rb, line 361 361: def method_missing(method, *args, &block) 362: if Array.method_defined?(method) 363: to_a.send(method, *args, &block) 364: elsif @klass.scopes[method] 365: merge(@klass.send(method, *args, &block)) 366: elsif @klass.respond_to?(method) 367: scoping { @klass.send(method, *args, &block) } 368: elsif arel.respond_to?(method) 369: arel.send(method, *args, &block) 370: else 371: super 372: end 373: end
# File lib/active_record/relation.rb, line 377 377: def references_eager_loaded_tables? 378: # always convert table names to downcase as in Oracle quoted table names are in uppercase 379: joined_tables = (tables_in_string(arel.joins(arel)) + [table.name, table.table_alias]).compact.map{ |t| t.downcase }.uniq 380: (tables_in_string(to_sql) - joined_tables).any? 381: end
# File lib/active_record/relation.rb, line 383 383: def tables_in_string(string) 384: return [] if string.blank? 385: # always convert table names to downcase as in Oracle quoted table names are in uppercase 386: # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries 387: string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_'] 388: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.