The root class of all active record objects.
set_table_name | -> | table_name= |
set_primary_key | -> | primary_key= |
set_inheritance_column | -> | inheritance_column= |
set_sequence_name | -> | sequence_name= |
scope_constraints | -> | scope_constrains |
backwards compatibility | ||
scope_constraints= | -> | scope_constrains= |
backwards compatibility | ||
sanitize_sql | -> | sanitize_conditions |
respond_to? | -> | respond_to_without_attributes? |
For checking respond_to? without searching the attributes (which is faster). | ||
connection= | -> | connection_without_query_cache= |
If this macro is used, only those attributes named in it will be accessible for mass-assignment, such as new(attributes) and attributes=(attributes). This is the more conservative choice for mass-assignment protection. If you’d rather start from an all-open default and restrict attributes as needed, have a look at attr_protected.
Attributes named in this macro are protected from mass-assignment, such as new(attributes) and attributes=(attributes). Their assignment will simply be ignored. Instead, you can use the direct writer methods to do assignment. This is meant to protect sensitive attributes from being overwritten by URL/form hackers. Example:
class Customer < ActiveRecord::Base attr_protected :credit_rating end customer = Customer.new("name" => David, "credit_rating" => "Excellent") customer.credit_rating # => nil customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" } customer.credit_rating # => nil customer.credit_rating = "Average" customer.credit_rating # => "Average"
Log and benchmark multiple statements in a single block. Example:
Project.benchmark("Creating project") do project = Project.create("name" => "stuff") project.create_manager("name" => "David") project.milestones << Milestone.find(:all) end
The benchmark is only recorded if the current level of the logger matches the log_level, which makes it easy to include benchmarking statements in production software that will remain inexpensive because the benchmark will only be conducted if the log level is low enough.
The logging of the multiple statements is turned off unless use_silence is set to false.
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 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 is available.
Returns the connection currently associated with the class. This can also be used to "borrow" the connection to do database work unrelated to any of the specific Active Records.
Add constraints to all queries to the same model in the given block. Currently supported constraints are :conditions and :joins
Article.constrain(:conditions => "blog_id = 1") do Article.find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 end
Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", and columns used for single table inheritance have been removed.
Returns the number of records that meet the conditions. Zero is returned if no records match. Example:
Product.count "sales > 1"
Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
Creates an object, instantly saves it as a record (if the validation permits it), and returns it. If the save fails under validations, the unsaved object is still returned.
Deletes the record with the given id without instantiating an object first. If an array of ids is provided, all of them are deleted.
Deletes all the records that match the condition without instantiating the objects first (and hence not calling the destroy method). Example:
Post.destroy_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
Destroys the record with the given id by instantiating the object and calling destroy (all the callbacks are the triggered). If an array of ids is provided, all of them are destroyed.
Destroys the objects for all the records that match the condition by instantiating each object and calling the destroy method. Example:
Person.destroy_all "last_login < '2004-04-04'"
Establishes the connection to the database. Accepts a hash as input where the :adapter key must be specified with the name of a database adapter (in lower-case) example for regular databases (MySQL, Postgresql, etc):
ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "myuser", :password => "mypass", :database => "somedatabase" )
Example for SQLite database:
ActiveRecord::Base.establish_connection( :adapter => "sqlite", :dbfile => "path/to/dbfile" )
Also accepts keys as strings (for parsing from yaml for example):
ActiveRecord::Base.establish_connection( "adapter" => "sqlite", "dbfile" => "path/to/dbfile" )
The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError may be returned on an error.
Returns true if the given id represents the primary key of a record in the database, false otherwise. Example:
Person.exists?(5)
Find operates with three different retrieval approaches:
All approaches accept an option hash as their last parameter. The options are:
Examples for find by id:
Person.find(1) # returns the object for ID = 1 Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6) Person.find([7, 17]) # returns an array for objects with IDs in (7, 17) Person.find([1]) # returns an array for objects the object with ID = 1 Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
Examples for find first:
Person.find(:first) # returns the first object fetched by SELECT * FROM people Person.find(:first, :conditions => [ "user_name = ?", user_name]) Person.find(:first, :order => "created_on DESC", :offset => 5)
Examples for find all:
Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50) Person.find(:all, :offset => 10, :limit => 10) Person.find(:all, :include => [ :account, :friends ])
Works like find(:all), but requires a complete SQL string. Examples:
Post.find_by_sql "SELECT p.*, c.author FROM posts p, comments c WHERE p.id = c.post_id" Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
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. This is used for caching aggregate values, so that they don’t need to be computed every time. Especially important for looping over a collection where each element require a number of aggregate values. Like the DiscussionBoard that needs to list both the number of posts and comments.
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). In both instances, valid attribute keys are determined by the column names of the associated table — hence you can’t have attributes that aren’t part of the table columns.
Defines the primary key field — can be overridden in subclasses. Overwriting will negate any effect of the primary_key_prefix_type setting, though.
Remove the connection for this class. This will close the active connection and the defined connection (if they exist). The result can be used as argument for establish_connection, for easy re-establishing of the connection.
Resets all the cached information about columns, which will cause them to be reloaded on the next request.
Specifies that the attribute by the name of attr_name should be serialized before saving to the database and unserialized after loading from the database. The serialization is done through YAML. If class_name is specified, the serialized object must be of that class on retrieval or SerializationTypeMismatch will be raised.
Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
Sets the name of the inheritance column to use to the given value, or (if the value # is nil or false) to the value returned by the given block.
Example:
class Project < ActiveRecord::Base set_inheritance_column do original_inheritance_column + "_id" end end
Sets the name of the primary key column to use to the given value, or (if the value is nil or false) to the value returned by the given block.
Example:
class Project < ActiveRecord::Base set_primary_key "sysid" end
Sets the name of the sequence to use when generating ids to the given value, or (if the value is nil or false) to the value returned by the given block. This is required for Oracle and is useful for any database which relies on sequences for primary key generation.
Setting the sequence name when using other dbs will have no effect. If a sequence name is not explicitly set when using Oracle, it will default to the commonly used pattern of: #{table_name}_seq
Example:
class Project < ActiveRecord::Base set_sequence_name "projectseq" # default would have been "project_seq" end
Sets the table name to use to the given value, or (if the value is nil or false) to the value returned by the given block.
Example:
class Project < ActiveRecord::Base set_table_name "project" 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 rules used to do the guess are handled by the Inflector class in Active Support, which knows almost all common English inflections (report a bug if your inflection isn’t covered).
Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended. So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a "mice" table. Example:
class Mouse < ActiveRecord::Base set_table_name "mice" end
Finds the record from the passed id, instantly saves it with the passed attributes (if the validation permits it), and returns it. If the save fails under validations, the unsaved object is still returned.
Updates all records with the SET-part of an SQL update statement in updates and returns an integer with the number of rows updated. A subset of the records can be selected by specifying conditions. Example:
Billing.update_all "category = 'authorized', approved = 1", "author = 'David'"
Returns the class type of the record using the current module as a prefix. So descendents of MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
Accepts an array or string. The string is returned untouched, but the array has each value sanitized and interpolated into the sql statement.
["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
Returns true if the comparison_object is the same object, or is of the same type and has the same id.
Returns the value of the attribute identified by attr_name after it has been typecast (for example, "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). (Alias for the protected read_attribute method).
Updates the attribute identified by attr_name with the specified value. (Alias for the protected write_attribute method).
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 respond to empty?, most notably Strings).
Returns a hash of all the attributes with their names as keys and clones of their objects as values.
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). Sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed in with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.
Returns the connection currently associated with the class. This can also be used to "borrow" the connection to do database work that isn’t easily done without going straight to SQL.
Initializes the attribute to zero if nil and subtracts one. Only makes sense for number-based attributes. Returns self.
Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).
Just freeze the attributes hash, such that associations are still accessible even on destroyed records.
Delegates to id in order to allow two records of the same type and id to work with something like:
[ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
Every Active Record class must use "id" as their primary ID. This getter overwrites the native id method, which isn’t being used in this context.
Initializes the attribute to zero if nil and adds one. Only makes sense for number-based attributes. Returns self.
Returns true if this object hasn’t been saved yet — that is, a record for the object doesn’t exist yet.
A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and person.respond_to?("name?") which will all return true.
Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. Note: This method is overwritten by the Validation module that’ll make sure that updates made with this method doesn’t get subjected to validation checks. Hence, attributes can be updated even if the full object isn’t valid.