ActiveRecord


1.         Table and class

By default,Active Record assumes that the name of the table is the plural form of the name of the class.But you can specify the name of the table which the class is corresponding in class with ‘set_table_name’ method or ‘table_name’ property. For example:

class Sheep < ActiveRecord::Base

set_table_name "sheep" # Not "sheeps"

end

class Order < ActiveRecord::Base

set_table_name "ord_rev99_x" # Wrap a legacy table...

end

class Sheep < ActiveRecord::Base

self.table_name = "sheep"

end

2.         APIs of ActiveRecord::Base

All these methods are Singleton method,so you should access these methods though neither an instance, nor the class.

(1)column_names:return all the name of columns in an array.

(2)column_hash[“column_name”]:return the detail of this column

(3)find(primay_key):If given just one primary key,it returns an object containing data for the corresponding row(or throws a RecordNotFound exception).If given multiple primary key values,find returns an array of the corresponding objects.

(4)primay_key:If you override the primary key column’s name with ‘primary_key’ method when you create a table,you can use this property to specify the primary key.For example:

class Book < ActiveRecord::Base

       self.primary_key = “column_name”

end

 

3.         Boolean Attribute

To query a column as a Boolean value in a condition,you must append a question mark to the column’s name.

4.         Connecting to the Database

One way of specifying the connection is to use the establish_connection class method.For example:

ActiveRecord::Base.establish_connection(

       :adapter   => “mysql”,

       :host       => “dbserver.com”

       :database => “railsdb”,

       :username=> “user”,

       :password=> “password”

)

5.         Connections and Models

Connections are associated with model classes.Each class inherits the connection of its parent.Because ActiveRecord::Base is the base class of all the Active Record classes,setting a connection for it sets the default connection for all the Active Record Classes you define.However,you can override this when you need to do so.

ActiveRecord::Base.establish_connection(

:adapter => "mysql" ,

:host => "dbserver.com" ,

:database => "online" ,

:username => "groucho" ,

:password => "swordfish" )

class LineItem < ActiveRecord::Base

# ...

end

class Order < ActiveRecord::Base

# ...

end

class Product < ActiveRecord::Base

# ...

end

class Customer < ActiveRecord::Base

establish_connection(

:adapter => "mysql" ,

:host => "dbserver.com" ,

:database => "backend" ,

:username => "chicho" ,

:password => "piano" )

# ...

end

aFinally,you can combine the two approaches(use establish_connection method or configure in database.yml file).If you pass a symbol to establish_connection, Rails looks for a section in database.yml with that name and bases the connection on the parameters found there.This way you can keep all connection details out of your code.

6.         CRUD

(1)    Create

use ‘new’ method to create an object and call the ‘save’ method of this object to save the data into database.

Active Record constructors take an optional block.If present,the block is invoked with the newly created order as a parameter.This might be useful if you wanted to create and save away an order without creating a new local variable.

Active Record constructors accept a hash of attribute values as an optional parameter. Each entry in this hash corresponds to the name and value of an attribute to be set.

 

You know that the ‘new’ method creates a new object in memory,we have to invoke ‘save’ method to save the data into database.Active Record has a convenience method,create, that both instantiates the model object and stores it into the database.

You can pass create an array of attribute hashes;it’ll create multiple rows in database and return an array of the corresponding model objects.

 

The real reason that new and create take a hash of values is that you can construct model objects directly from form parameters.For example:

order = Order.new(params[:order])

(2)    Read

l         find:

If given just one primary key,it returns an object containing data for the corresponding row(or throws a RecordNotFound exception).If given multiple primary key values,find returns an array of the corresponding objects.

:first and :all --The :first variant of find returns the first row that matches a set of criteria, while the :all form eturns an array of matching rows.

:condition—determines which rows are returned by the find;it corresponds to an SQL where clause.

how to generate dynamic SQL:

One way of specifying placeholders is to insert one or more question marks in the SQL.The first question mark is replaced by the second element of the array,the next question mark by the third,and so on.For example:

name = params[:name]

pos = Order.find(:all,

:conditions => ["name = ? and pay_type = 'po'" , name])

                 You can alse use named placeholders.

                     name = params[:name]

pay_type = params[:pay_type]

pos = Order.find(:all,

:conditions => ["name = :name and pay_type = :pay_type" ,

{:pay_type => pay_type, :name => name}])

:order—The :order parameter lets you specify the criteria you’d normally and after the order by keywords.

:limit—You can limit the number of rows returned.

:offset—The :offset parameter goes hand in hand with the :limit parameter.It allows you to specify the the offset of the first row in the result set that will be returned.For example:

def Order.find_on_page(page_num, page_size)

find(:all,

:order => "id" ,

:limit => page_size,

:offset => page_num*page_size)

end

:joins—The :joins parameter to the finder method lets you specify a list of additional tables to be joined to the default table.

:select—The :select parameter takes a string which will appear in the place of the * in the select statement.

:readonly—If :readonly is set to true,Active Record objects returned by find cannot be stored back in to database.If you use the :joins or :select options,objects will automatically be marked :readonly.

:form—The :form option lets you override the table name inserted into the select clause.

:group—The :group option adds a group by clause to the SQL generated by find.

:lock—The :lock option takes either a string or the constrant true.

l         find_by_sql

The method find_by_sql lets your application take full control.

l         Column Statistics

average(:column_name)

maximum(:column_name)

minimum(:column_name)

sum(:column_name)

count

All the functions take a hash of options,very similar to the hash that can be passed to find.

:conditions

:joins

:limit

:order

:having

:select

:distinct(for count only)

l         Dynamic Finders

If you invoke a model’s class method where the method name starts find_by_ or find_all_by_,Active Record converts it to a finder,using the rest of the method’s name to determine the column to be checked. find_by_XXX is converted to find(:first,:conditions=>XXX…).Similary,find_all_by_XXX is converted into matching find(:all,…) calls.

find_by_name_and_password(name,pw)

(3)    Updating Existing Rows

update_attribute(Object method) can be called by an object which exists in database.

update(Class method) need pass the id into this method

update_all(Class method) update all rows

(4)    Deleting Rows

delete—The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table.

delete_all—The delete_all method deletes rows matching a given condition(or all rows if no condition is specified).

destroy

destroy_all

7.         Composing Data with Aggregations

You define a class to hold the data,and you add a declaration to the model class telling it to map the database column(s) to and from objects of the dataholder class.

composed_of :attr_name, :class_name => SomeClass, :mapping => mapping

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值