`
reverocean
  • 浏览: 195447 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

ActiveRecord

    博客分类:
  • Ruby
阅读更多


<!---->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

分享到:
评论

相关推荐

    ActiveRecord简单实例_activerecord.zip

    在Ruby on Rails框架中,ActiveRecord是一个至关重要的组件,它负责模型(Model)与数据库之间的交互。本实例将深入探讨ActiveRecord的基本用法,帮助理解如何在实际开发中有效地运用这个强大的工具。 首先,让我们...

    Pro ActiveRecord Databases with Ruby and Rails.pdf

    ### ActiveRecord在Ruby与Rails中的高级应用 #### 一、引言 《Pro ActiveRecord Databases with Ruby and Rails》这本书深入探讨了如何使用ActiveRecord框架来高效地处理Ruby on Rails中的数据库操作。本书由Kevin ...

    Castle.ActiveRecord (.NET FrameWork 2.0)

    Castle.ActiveRecord For .NET FrameWork 2.0 如果你想使用Castle.ActiveRecord,但又不想使用.NET Framework 3.0/3.5/4.0或更高版本,那么这个就是你所需要的,For .NET FrameWork 2.0,我整理了好久,自己从官方...

    NHibernate中文教程+activerecord

    Castle ActiveRecord是NHibernate ActiveRecord实现的一个版本,提供了额外的功能和方便性。它是一个AOP(面向切面编程)框架,能够自动管理对象的生命周期,包括事务、验证和持久化。 9. **最佳实践** 在实际...

    Castle.ActiveRecord 升级NHibernate到3.4.0GA

    Castle.ActiveRecord官方已经停止更新了,官方最高支持到NHibernate 3.1.0.4000,这个版本还有不少问题(例如:[NH-2213] - CLONE -Wrong parameters order in IQuery with SetParameterList and Filter)。...

    C# Castle.ActiveRecord CS源码示例教程.zip

    《C# Castle.ActiveRecord 源码示例教程》 Castle.ActiveRecord 是一款基于 C# 的轻量级对象关系映射(ORM)框架,它为 .NET 开发者提供了简化数据库交互的方式。这个教程主要围绕如何使用 Castle.ActiveRecord 在...

    简单Castle.ActiveRecord.Generator

    Castle.ActiveRecord.Generator 是一个基于 Castle ActiveRecord 框架的代码生成工具,它极大地简化了在.NET环境中使用ActiveRecord模式进行数据库操作的工作流程。ActiveRecord是面向对象持久化的一个设计模式,将...

    scala-activerecord-specs_2.9.2-0.2.3.zip

    描述中提到"scala-activerecord.zip",这可能是Scala Activerecord的主要库文件,而"scala activerecord scalatraactiverecord"则暗示Scala Activerecord可能与ScalatraActiverecord有关,ScalatraActiverecord是一...

    [IronRuby] C# 4.0调用ActiveRecord

    从提供的文件信息中,我们可以得知这篇博文主要讨论的是如何使用C# 4.0调用IronRuby中的ActiveRecord功能。不过由于博文链接和部分详细内容无法提供,知识点将基于文件信息部分和公共知识构建。 知识点一:IronRuby...

    MyBatisPlus的ActiveRecord实现CRUD示例代码

    在本示例中,我们将深入探讨MyBatisPlus如何通过ActiveRecord模式实现CRUD(创建、读取、更新、删除)操作。ActiveRecord是一种设计模式,它将数据库表中的每一条记录映射为一个对象,通过这个对象可以直接进行CRUD...

    Java敏捷持久层-ROR-ActiveRecord持久层框架的Java实现

    在Java世界里,虽然Hibernate和JPA等框架已经非常成熟,但Ruby on Rails(ROR)中的ActiveRecord模式也受到了不少Java开发者的青睐,并有了一些移植到Java平台的实现。 ActiveRecord是一种对象关系映射(ORM)模式...

    Ruby-SchemaPlus提供增强和扩展ActiveRecord的集合

    **Ruby-SchemaPlus:增强与扩展ActiveRecord的宝藏** 在Ruby on Rails开发中,ActiveRecord是核心组件之一,它作为ORM(对象关系映射)工具,使得开发者可以以面向对象的方式处理数据库操作。然而,尽管...

    Ruby-OccamsRecord缺少ActiveRecord的高效查询API

    Ruby是一种动态、面向对象的编程语言,而ActiveRecord是Ruby on Rails框架中的一个核心组件,它是一个对象关系映射(ORM)系统。ActiveRecord提供了一种简洁的方式将数据库操作与Ruby对象模型化,使得开发者可以方便...

    ActiveRecord 升级NHibernate到3.3.0GA

    将ActiveRecord中的NHibernate升级到3.3.0GA,排除编译的bug问题,保留ActiveRecord的完整功能,【Castle.ActiveRecord 升级NHibernate到3.4.0GA】的功能不完整!

    C# Castle.ActiveRecord Winform 源码示例教程

    Castle.ActiveRecord 的资料很多,但是WINFORM的没几个,于此我专门写了个例子献给初学Castle.ActiveRecord的童鞋们,希望这篇文档能够帮到你们。这个例子使用的是ACCESS数据库,从单表,一对多,多对多,数据绑定,...

    userstamp, 这个 Rails 插件扩展ActiveRecord.zip

    userstamp, 这个 Rails 插件扩展ActiveRecord Userstamp插件( v-2.0 )概述Userstamp插件扩展了 ActiveRecord::Base,以添加对'创建者','更新程序'和'deleter'属性的自动更新。 它是基于 ActiveRecord::Timesta

    ActiveRecord最终版(已更新NHibernate.3.4.1.4000)

    ActiveRecord最终版,由于ActiveRecord引用了ISet集合,Iesi.Collections.3.4.1.4000以后已经把ISet去掉了,所以ActiveRecord引用的NHibernate的版本的更新只能到3.4.1.4000此为止。 引用其他资源版本如下: ...

    activerecord-oracle-adapter-1.0.0.9250.gem

    activerecord-oracle-adapter-1.0.0.9250.gem 我找了很久才找到的,希望能解决部分像我这样,需要的同志!分就不要了,我就搬运了下,希望能解决部分人的问题!

    Castle ActiveRecord快速入门指南、ActiveRecord帮助文档

    Castle ActiveRecord 是一个开源框架,它是基于 .NET 平台的,用于简化对象关系映射(ORM)的过程。这个框架借鉴了 Ruby on Rails 中的 ActiveRecord 模式,将业务对象与数据库记录关联起来,使得开发者可以更专注于...

    castle ActiveRecord 源代码

    《Castle ActiveRecord源代码解析——基于NHibernate的C#封装实践》 Castle ActiveRecord是.NET框架下的一款优秀的ORM(对象关系映射)工具,它基于流行的NHibernate库进行了高级封装,为开发者提供了更加简洁、...

Global site tag (gtag.js) - Google Analytics