
8474_chAppAFINAL.qxd 8/25/07 9:17 AM Page 215 APPENDIX ■ ■ ■ Active Record Methods in Detail ActiveRecord::Base Public Class Methods ==(object_to_compare) This method returns true if the object_to_compare is the same as the receiving object or is of the same Active Record class and has the same ID. [](attribute_name) This method returns the value of the specified attribute after it has been typecast and is an alias for the protected read_attribute method of an Active Record class. While a common method of accessing the attributes of an Active Record class is via a method call, like account.first_name, Active Record overrides the [] operator to make each of the attributes available as a hash parameter on the Active Record class. For example, you can also use the form account[:first_name]. []==(attribute_name, new_value) This method is an alias for the protected write_attribute method of an Active Record class, and it allows you to set attribute values using a hash-like syntax, for example: account[:last_name] = "Pytel" abstract_class?() abstract_class? returns true if the specified Active Record class is a base Active Record class and false if it is not. attr_accessible(*attributes) This method takes an array of attributes and makes them the only available attributes for mass assignment operations, such as with new(attributes) and attributes=(attributes). All other attributes of the Active Record class become unavailable for mass assignment operations. The attr_protected(*attributes) method is the reverse of this operation. 215 8474_chAppAFINAL.qxd 8/25/07 9:17 AM Page 216 216 APPENDIX ■ ACTIVE RECORD METHODS IN DETAIL attr_protected(*attributes) This method takes an array of attributes and makes them unavailable for mass assignment operations, such as new(attributes) and attributes=(attributes). All other attributes of the Active Record class remain unchanged. The attr_accessible(*attributes) method is the reverse of this method. base_class() base_class returns the base Active Record class from which the specified Active Record class descends. benchmark(title, log_level = Logger::DEBUG, use_silence = true) {|| . .} This method logs and benchmarks the statements that are specified in its block: Account.benchmark("Creating and Finding Account") do account = Account.new(:username = > "cpytel") account.save accout.find_by_username("cpytel") end The benchmark is only performed if the current logging level matches the specified log_level. This allows you to specify benchmarking calls in production software without worrying about a performance hit from the benchmark. Logging multiple statements of the benchmark is enabled by default but can be turned off by passing false to use_silence. clear_active_connections!() The method clears the cache that maps classes to database connections. column_names() column_names returns an array of strings that are the column names for the database table associated with this Active Record class. columns() With columns, you can return an array of column objects for the database table associated with this Active Record class. columns_hash() This method returns a hash of column objects for the database table associated with this Active Record class. 8474_chAppAFINAL.qxd 8/25/07 9:17 AM Page 217 APPENDIX ■ ACTIVE RECORD METHODS IN DETAIL 217 connected?() The connected? method returns true if a database connection that is usable by this class has been opened. connection() To return the connection currently associated with the class, use the connection method. This method can also be used to obtain the connection in order to work directly with the database, for example: Account.connection.select_values("SELECT id FROM accounts WHERE created_at < " + Time.now – 1.day) connection=(connection_specification) This method manually sets the database connection for an Active Record class. content_columns() This method returns an array of column objects that Active Record considers the actual con- tent, or data, of the Active Record class. Therefore, this array does not include the primary ID column, any columns ending in _id or _count, and any columns used for single table inheritance. count_by_sql(sql_query_string) The method returns the result of an SQL query that should only include COUNT(*) in the SELECT part of the SQL query: Account.count_by_sql("SELECT COUNT(*) FROM accounts") create(attributes = nil) The create method instantiates and immediately saves the Active Record class with the values specified in the attributes hash, if validations permit. The newly created Active Record object is returned regardless of whether the save succeeded. decrement_counter(counter_name, id) This method works just like the increment_counter(counter_name, id) method, but it decre- ments the counter instead. delete(id) This method deletes the database record with the given id but does not instantiate the object first. Therefore, the destroy method and any other callbacks are not triggered. If an array of IDs is provided, all of the records matching the IDs are deleted. 8474_chAppAFINAL.qxd 8/25/07 9:17 AM Page 218 218 APPENDIX ■ ACTIVE RECORD METHODS IN DETAIL delete_all(conditions = nil) This method deletes all of the database records that match the given conditions but does not instantiate the objects first. Therefore, the destroy method and any other callbacks are not triggered. The format of conditions is the same as those given to the find method. If no condi- tions are specified, all of the database records for this class will be removed. destroy(id) destroy removes the database record associated with the given primary key by first instantiat- ing the object and then calling the destroy method on the object. Therefore, when using this method, the destroy callbacks are triggered. If an array of IDs is provided, all of the records matching the IDs are destroyed. destroy_all(conditions = nil) Use this method to destroy all the database records that match the given conditions by first instantiating each object and then calling the destroy method. Therefore, when using this method, the destroy callbacks are triggered. The format of conditions is the same as those given to the find method. If no conditions are specified, all of the database records for this class will be destroyed. establish_connection(connection_specification = nil) This method is used to establish a connection to a database. It accepts a hash of connection parameters, where the :adapter key must be specified with the name of a valid database adapter: ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "project", :database => "project_development") exists?(id) exists? returns true if the specified id matches the primary key of a record in the database. find(*args) The find method can retrieve a record by its id, the first record matching a query, or all records matching a query. When retrieving records by id, the find method can take a single id, a list of ids, or an array of ids, as shown in the following examples: Account.find(1) Account.find(1, 2, 3) Account.find([1, 2, 3]) Return only the first matching record like this: Account.find(:first) 8474_chAppAFINAL.qxd 8/25/07 9:17 AM Page 219 APPENDIX ■ ACTIVE RECORD METHODS IN DETAIL 219 Return all matching records like this: Account.find(:all) All of these approaches to returning records take an optional hash as the final parameter. The valid options in this hash follow: :conditions: The :conditions options supplied to the find method will be converted into the WHERE clause of the SQL statement. You can pass a string or a hash of column names and values, or you can specify a more complex string of SQL along with values to interpo- late inside an Array. :order: The :order parameter defines the sorting order that would normally appear in the ORDER clause of the resulting SQL statement. When you specify the :order option, you are literally specifying a snippet of the SQL statement that will be sent to your database server. :group: The :group parameter defines the GROUP BY portion of the resulting SQL statement, and like the :order parameter, the string supplied will directly translate to the GROUP BY portion of the SQL statement. :limit: The :limit parameter takes an integer and directly corresponds to the LIMIT portion of the resulting SQL statement. :offset: The :offset parameter takes an integer and directly corresponds to the OFFSET portion of the resulting SQL statement. :include: The :include option is used to augment the FROM portion of the resulting SQL statement. The :include parameter will take a nested hash of symbols that correspond to the names of relationships you’ve defined for your model and add use them as joining conditions. :joins: While the :joins parameter is similar in function to the :include option, it works on a lower level in the resulting SQL statement. The value given to the :joins option is a string that will get added to the FROM clause of the SQL statement. You can use this to join on tables to which you don’t have a defined Active Record relationship. :from: Whereas the :joins option will let you specify extra tables to join to in the FROM clause, the :from option allows you to specify the entire contents of the FROM clause of the SQL statement. :select: You can use the :select option to specify extra columns in the SELECT clause of the resulting SQL statement. Any extra columns will be added as additional attributes on the returned objects, called piggyback attributes. However, because Active Record doesn’t know how to save these extra attributes, the objects it returns will automatically be marked as read only. :readonly: Specifying true for this parameter will mark the records returned from this find call as read only and prevent changes to the objects from being saved. Likewise, specifying false for this parameter will ensure that the records returned will not be marked as read only, regardless of whether they should (such as when the :select parameter is used). 8474_chAppAFINAL.qxd 8/25/07 9:17 AM Page 220 220 APPENDIX ■ ACTIVE RECORD METHODS IN DETAIL :lock: You can use the :lock option to have the database lock the selected rows.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages66 Page
-
File Size-