ActiveRecord::Base (Class)

In: lib/active_record/base.rb
lib/active_record/connection_adapters/dbi_adapter.rb
lib/active_record/connection_adapters/mysql_adapter.rb
Parent: Object

External Aliases

method_missing -> method_really_missing

Public Class methods

Returns an instance of this class with the values of the row responding to the id parameter.

[Source]

    # File lib/active_record/base.rb, line 7
 7:       def find(id)
 8:         sql = "SELECT * FROM #{table_name} WHERE id = #{id.to_i} "
 9:         sql << "AND type = '#{name}'" unless descents_from_active_record?
10: 
11:         if row = connection.select_one(sql, "#{name} Find")
12:           instantiate(row)
13:         else 
14:           raise Exception, "Couldn't find #{name} with ID = #{id}"
15:         end
16:       end

Works like find, but rows matching id must also fulfill the constraint or an exception is thrown.

[Source]

    # File lib/active_record/base.rb, line 19
19:       def find_with_constraint(id, constraint)
20:         if active_record = find_first("id = #{id.to_i} AND #{sanitize_conditions(constraint)}")
21:           return active_record
22:         else
23:           raise(Exception, "Couldn't find #{name} with ID = #{id} constrained by #{constraint}")
24:         end
25:       end

Returns an array of all the ActiveRecord objects that could be instantiated from the associated table in the database. The conditions can be used to narrow the selection of objects, such as by "color = ‘red’", and arrangement of the selection can be done through orderings, such as by "last_name, first_name DESC". A maximum of returned objects can be specified in limit.

[Source]

    # File lib/active_record/base.rb, line 31
31:       def find_all(conditions = nil, orderings = nil, limit = nil)
32:         sql  = "SELECT * FROM #{table_name} " 
33:         add_conditions!(sql, conditions)
34:         sql << "ORDER BY #{orderings} " unless orderings.nil?
35:         sql << "LIMIT #{limit} "    unless limit.nil?
36:     
37:         find_by_sql(sql)
38:       end

Works like find_all, but requires a complete SQL string.

[Source]

    # File lib/active_record/base.rb, line 41
41:       def find_by_sql(sql)
42:         connection.select_all(sql, "#{name} Load").inject([]) { |objects, row| objects << instantiate(row) }
43:       end

Returns a single ActiveRecord object responding to the conditions in conditions, such as "group = ‘master’". If more than one row is returned from the SQL query, it’s the first that’ll be used to create the ActiveRecord object. In such cases, it might be beneficial to also specify orderings, like "income DESC, name", to control exactly which row is to be used.

[Source]

    # File lib/active_record/base.rb, line 49
49:       def find_first(conditions = nil, orderings = nil)
50:         sql  = "SELECT * FROM #{table_name} "
51:         add_conditions!(sql, conditions)
52:         sql << "ORDER BY #{orderings} " unless orderings.nil?
53:         sql << "LIMIT 1"
54:     
55:         row = connection.select_one(sql, "#{name} Load First")
56:         instantiate(row) unless row.nil?
57:       end

Updates all ActiveRecord rows with the SQL update segment from updates. A subset of the ActiveRecord rows can be selected by specifying a SQL conditions segment in conditions.

[Source]

    # File lib/active_record/base.rb, line 61
61:       def update_all(updates, conditions = nil)
62:         sql  = "UPDATE #{table_name} SET #{updates} "
63:         add_conditions!(sql, conditions)
64:         connection.update(sql, "#{name} Update")
65:       end

Destroys all the ActiveRecord rows for this class that matches the condition_sql by instantiating the objects and calling the destroy method.

[Source]

    # File lib/active_record/base.rb, line 69
69:       def destroy_all(conditions = nil)
70:         find_all(conditions).each { |o| o.destroy }
71:       end

Deletes all the ActiveRecord rows for this class that matches the condition_sql without instantiating the objects first.

[Source]

    # File lib/active_record/base.rb, line 74
74:       def delete_all(conditions = nil)
75:         sql = "DELETE FROM #{table_name} "
76:         add_conditions!(sql, conditions)
77:         connection.delete(sql, "#{name} Delete all")
78:       end

Returns the number of rows that meets the passed-in conditions.

[Source]

    # File lib/active_record/base.rb, line 81
81:       def count(conditions = nil)
82:         sql  = "SELECT COUNT(*) FROM #{table_name} "
83:         add_conditions!(sql, conditions)
84:         count_by_sql(sql)
85:       end

Returns the result of a SQL statement that should only include a COUNT(*) in the SELECT part.

[Source]

    # File lib/active_record/base.rb, line 88
88:       def count_by_sql(sql)
89:         count = connection.select_one(sql, "#{name} Count").values.first
90:         return count ? count.to_i : 0
91:       end

Increments the specified counter by one. So DiscussionBoard.increment_counter("post_count", discussion_board_id) would increment the "post_count" counter on the board responding to discussion_board_id.

[Source]

    # File lib/active_record/base.rb, line 95
95:       def increment_counter(counter_name, id)
96:         active_record = find(id)
97:         active_record.send("#{counter_name}=", active_record.send(counter_name) + 1)
98:         active_record.save
99:       end

Returns the connection currently held by the class. This can be used to "borrow" the connection to do database work unrelated to any of the specific Active Records.

[Source]

     # File lib/active_record/base.rb, line 103
103:       def connection
104:         if @@connection.nil? then raise "No database connection has been set" end
105:         @@connection
106:       end

Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used to guess the table name from even when called on Reply. The guessing rules are as follows:

  • Class name doesn’t end in "s" or "y": An "s" is appended, so a Comment class becomes a comments table.
  • Class name ends in a "y": The "y" is replaced with "ies", so a Category class becomes a categories table.
  • Class name ends in an "s": No additional characters are added or removed.
  • Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.

Overwrite this class method to allow for unguessable links, such as a Person class with a link to a People table.

[Source]

     # File lib/active_record/base.rb, line 117
117:       def table_name
118:         class_name = class_name_of_active_record_descendant(self)
119: 
120:         class_name.gsub!(/([a-z])([A-Z])/, '\1_\2')
121:         class_name.downcase!
122: 
123:         case class_name[-1,1]
124:           when "s"
125:             class_name
126:           when "y"
127:             class_name[0..-2] + "ies"
128:           else
129:             class_name + "s"
130:         end
131:       end

Decrements the specified counter by one. So DiscussionBoard.decrement_counter("post_count", discussion_board_id) would decrement the "post_count" counter on the board responding to discussion_board_id.

[Source]

     # File lib/active_record/base.rb, line 135
135:       def decrement_counter(counter_name, id)
136:         active_record = find(id)
137:         active_record.send("#{counter_name}=", active_record.send(counter_name) - 1)
138:         active_record.save
139:       end

Transforms attribute key names into a more humane format, such as "First name" instead of "first_name"

[Source]

     # File lib/active_record/base.rb, line 160
160:       def human_attribute_name(attribute_key_name)
161:         attribute_key_name.gsub(/_/, " ").capitalize unless attribute_key_name.nil?
162:       end

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). If instantiated as empty, the valid attribute methods are constructed from the column names of the associated table — hence you can’t have attributes that aren’t part of the table columns, like you can with pre-set attributes.

[Source]

     # File lib/active_record/base.rb, line 223
223:       def initialize(attributes = nil)
224:         @attributes = attributes || attributes_from_column_definition
225:         @errors = Errors.new(self)
226:       end

[Source]

    # File lib/active_record/connection_adapters/dbi_adapter.rb, line 8
 8:     def self.establish_dbi_connection(uri, username = nil, password = nil, logger = nil)
 9:       self.connection = ConnectionAdapters::DBIAdapter.new(
10:         DBI.connect(uri, username, password), 
11:         logger
12:       )
13:     end

[Source]

    # File lib/active_record/connection_adapters/mysql_adapter.rb, line 9
 9:     def self.establish_mysql_connection(host, username, password, table, logger = nil)
10:       self.connection = ConnectionAdapters::MysqlAdapter.new(
11:         Mysql::real_connect(host, username, password, table), 
12:         logger
13:       )
14:     end

Public Instance methods

Every ActiveRecord class must use "id" as their primary ID. This getter overwrites the native id method, which isn’t being used in this context.

[Source]

     # File lib/active_record/base.rb, line 230
230:       def id
231:         @attributes["id"]
232:       end

Sets the primary ID.

[Source]

     # File lib/active_record/base.rb, line 235
235:       def id=(value)
236:         @attributes["id"] = value
237:       end

Returns true if this active record hasn’t been saved yet — that is a table row for the object doesn’t exist yet.

[Source]

     # File lib/active_record/base.rb, line 240
240:       def new_record?
241:         id.nil?
242:       end

id.nil?: Creates a new row with values matching those of the instant attributes.<br> !id.nil?: Updates the associated row with values matching those of the instant attributes.

[Source]

     # File lib/active_record/base.rb, line 246
246:       def save
247:         if valid? then create_or_update; true else false end
248:       end

Deletes the associated row in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).

[Source]

     # File lib/active_record/base.rb, line 252
252:       def destroy
253:         connection.delete "DELETE FROM #{self.class.table_name} WHERE id = #{id}", "#{self.class.name} Destroy"
254:         freeze
255:       end

Runs validate and returns true if no errors were added otherwise false.

[Source]

     # File lib/active_record/base.rb, line 258
258:       def valid?
259:         errors.clear
260:         validate
261:         if new_record? then validate_on_create else validate_on_update end
262:         errors.empty?
263:       end

[Source]

     # File lib/active_record/base.rb, line 265
265:       def errors
266:         @errors
267:       end

Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).

[Source]

     # File lib/active_record/base.rb, line 271
271:       def attributes=(attributes)
272:         @attributes.update(attributes)
273:       end

Returns true if the specified attribute has been set by the user or by a database load and is neither nil nor empty? (the latter only applies to objects that responds to empty?, most notably Strings).

[Source]

     # File lib/active_record/base.rb, line 277
277:       def attribute_present?(attribute)
278:         is_empty = @attributes[attribute].respond_to?("empty?") ? @attributes[attribute].empty? : false
279:         @attributes.include?(attribute) && !@attributes[attribute].nil? && !is_empty
280:       end

[Validate]