Ruby on Rails 2.0的新特性介绍

万众瞩目的Ruby on Rails 2.0已经发布了,Rails框架在2004年诞生以来,一直保持着相当快的版本升级速度:2005年发布了Rails1.0版本,2006年初发布Rails1.1版本,2007年初发布Rails1.2版本,而还没有等到2008年,在2007年圣诞前夕的12月6日,Rails2.0已经发布。

Rails框架每个大的版本升级都给我们带来了相当多的新功能,新惊喜。Rails1.0带给我们完善的单元测试和集成测试;Rails1.1带给我们DataBase Migration和RJS;Rails1.2让我们看到了REST的光明前景,那么Rails2.0又将带给我们什么呢? 我粗略的翻译了一下Rails框架作者DHH写的Rails2.0框架介绍文章,以下翻译自DHH的文章,原文在:

http://weblog.rubyonrails.org/2007/12/7/rails-2-0-it-s-done


在经过差不多一年的开发之后,Rails2.0终于发布了。这是一个棒极了的Rails版本,包括了大量堪称伟大的新特性,无数的bugfix和大量功能的打磨。我们花了无数的精力去打造这样一个非常完美合理的软件包。

这也是Rails框架发展历史上的一个里程碑。我个人在Rails框架上面的开发工作已经有四年半的时间了,并且我们现在的贡献者也越来越多。我对这几年我们所做出的工作和我们一直坚持的信念感到非常的满意。我们一直在坚持这一点并且不断推动它。

在详细的介绍Rails2.0之前,我要向那些为Rails框架做出过贡献的每一个人致以深深的谢意,不论是像一个家庭那样其乐融融的Rails核心开发团队,还是成千上万的、而且年复一年为Rails提交补丁,积极参与Rails社区人们。Rails2.0也是大规模开源软件开发社区的一个重大胜利,而你完全可以自豪于你在Rails社区当中扮演的角色和做出的贡献。干杯!

现在让我们简单的窥一斑见全豹的看看Rails的那些闪闪发光的特性:


Action Pack: Resources

Controller里面充斥着大量action方法的时代已经过去了,我们对REST架构的应用进行了大量的改进和提高。首先,我们不再使用分号来隔离自定义的方法,而是采用斜线,例如原来是 /people/1;edit的URL,现在改成了 /people/1/edit.另外我们还对URL路由资源添加了命名空间的支持,因此像后台管理的接口你可以像这样非常简单的定义:

Ruby代码 复制代码
  1. map.namespace(:admindo |admin|   
  2.   admin.resources :products,   
  3.     :collection => { :inventory => :get },   
  4.     :member     => { :duplicate => :post },   
  5.     :has_many   => [ :tags:images:variants ]   
  6. end  
map.namespace(:admin) do |admin|
  admin.resources :products,
    :collection => { :inventory => :get },
    :member     => { :duplicate => :post },
    :has_many   => [ :tags, :images, :variants ]
end


这种方式可以让你按照如下的方式定义命名路由,例如:inventory_admin_products_url和 admin_product_tags_url等等。为了方便的记录所有的路由规则,我们添加了一个rake任务叫做“rake routes”,它能够列举出来routes.rb定义的所有命名路由规则。

此外我们还引入了一个新的约定,即所有基于资源的controller默认都是复数形式的。这样即便单个资源在不同的路由规则中被多次引用,仍然可以指向同一个controller来处理,例如:

Ruby代码 复制代码
  1. # /avatars/45 => AvatarsController#show   
  2. map.resources :avatars  
  3.   
  4. # /people/5/avatar => AvatarsController#show    
  5. map.resources :people:has_one => :avatar  
# /avatars/45 => AvatarsController#show
map.resources :avatars

# /people/5/avatar => AvatarsController#show 
map.resources :people, :has_one => :avatar


Action Pack: Multiview

与资源映射一起进行功能增强的还有MultiView。我们已经有了respond_to方法,但我们可以更进一步,把MultiView控制延伸到模板里面去。我们现在可以根据模板文件的后缀格式来决定使用什么render机制。因此,show.rhtml你可以写成show.rhtml.erb,这就表明是一个默认的rhtml模板,和你过去在Action里面使用respond_to声明的format.html是一个意思。此外你还可以使用诸如show.csv.erb,它表明显示为csv格式的数据,并且使用默认的erb去render它。

所以,新的模板格式是: action.format.renderer。例如:
* show.erb: 不管什么格式的显示方式都使用默认的erb显示show模板
* index.atom.builder: 用Builder库来render XML文件,输出的文件类型为RSS的AOTM类型
* edit.iphone.haml: 使用用户自己定义的HAML render机制来输出模板内容到iPhone手机上面

说到iPhone手机,我们可以自己造一个专用的类型来实现内部路由。当你需要类似iPhone这样的特殊的HTML接口的时候,我们所要做的就是:

Ruby代码 复制代码
  1. # should go in config/initializers/mime_types.rb   
  2. Mime.register_alias "text/html":iphone  
  3.   
  4. class ApplicationController < ActionController::Base   
  5.   before_filter :adjust_format_for_iphone  
  6.   
  7.   private   
  8.     def adjust_format_for_iphone   
  9.       if request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(iPhone|iPod)/]   
  10.         request.format = :iphone  
  11.       end  
  12.     end  
  13. end  
  14.   
  15. class PostsController < ApplicationController   
  16.   def index   
  17.     respond_to do |format|   
  18.       format.html   # renders index.html.erb   
  19.       format.iphone # renders index.iphone.erb   
  20.     end  
  21.   end  
  22. end  
  # should go in config/initializers/mime_types.rb
  Mime.register_alias "text/html", :iphone

  class ApplicationController < ActionController::Base
    before_filter :adjust_format_for_iphone

    private
      def adjust_format_for_iphone
        if request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(iPhone|iPod)/]
          request.format = :iphone
        end
      end
  end

  class PostsController < ApplicationController
    def index
      respond_to do |format|
        format.html   # renders index.html.erb
        format.iphone # renders index.iphone.erb
      end
    end
  end


你完全可以在config/initializers/mime_types.rb里面注册自己的mime type类型的映射,这个文件默认已经提供了。


Action Pack: Record identification

为了驱使你使用基于资源的映射,我们对资源映射的controller和view的URL处理进行了大量的简化。我们添加了大量的命名约定,让你可以直接把model对象转化为资源映射的路由,例如:

Ruby代码 复制代码
  1. # person is a Person object, which by convention will    
  2. # be mapped to person_url for lookup   
  3. redirect_to(person)   
  4. link_to(person.name, person)   
  5. form_for(person)  
  # person is a Person object, which by convention will 
  # be mapped to person_url for lookup
  redirect_to(person)
  link_to(person.name, person)
  form_for(person)



Action Pack: HTTP Loving

如你所期望的那样,Rails2.0的Action Pack更加贴近HTTP,并且充分利用HTTP协议,例如资源、多种视图,还有更多的呢。我们添加了一个模块来处理HTTP的Basic验证,它能够让授权的API轻松跨越SSL协议,而且他是如此的简单易用。下面是一个例子(更多的例子请参考ActionController::HttpAuthentication):

Ruby代码 复制代码
  1. class PostsController < ApplicationController   
  2.   USER_NAME, PASSWORD = "dhh""secret"    
  3.   
  4.   before_filter :authenticate:except => [ :index ]   
  5.   
  6.   def index   
  7.     render :text => "Everyone can see me!"    
  8.   end  
  9.   
  10.   def edit   
  11.     render :text => "I'm only accessible if you know the password"    
  12.   end  
  13.   
  14.   private   
  15.     def authenticate   
  16.       authenticate_or_request_with_http_basic do |user_name, password|    
  17.         user_name == USER_NAME && password == PASSWORD   
  18.       end  
  19.     end  
  20. end  
  class PostsController < ApplicationController
    USER_NAME, PASSWORD = "dhh", "secret" 

    before_filter :authenticate, :except => [ :index ]

    def index
      render :text => "Everyone can see me!" 
    end

    def edit
      render :text => "I'm only accessible if you know the password" 
    end

    private
      def authenticate
        authenticate_or_request_with_http_basic do |user_name, password| 
          user_name == USER_NAME && password == PASSWORD
        end
      end
  end


此外,我们也做了很多工作让你把JavaScript和CSS文件组织到一个逻辑单元里面去,而不需要让浏览器发起多次HTTP请求,分别获取每个JavaScript和CSS文件,以便减少HTTP请求次数。使用javascript_include_tag(:all, :cache => true) 这个helper在生产环境下自动把public/javascripts/目录下面的所有js文件打包到单个public/javascripts/all.js文件里面,但在开发环境下,仍然保持每个文件独立的修改。

我们还添加了一些选项让,仅仅几行代码,就能够让浏览器去访问多台服务器上面的资源。如果你添加如下设置:ActionController::Base.asset_host = “assets%d.example.com”,那么Rails框架就会自动的把静态资源的请求分发到多台物理服务器上面去,例如分发到assets1.example, assets2.example.com, assets3.example.com等等。这样浏览器可以同时向多台服务器下载资源,增加你的应用的访问速度。


Action Pack: Security

能够很简单的创建出来安全的应用总是一件令人愉快的事情,而Rails2.0提供了大量先进的功能来达到这一点。非常重要的是我们现在提供了一种内建的机制来处理CRSF攻击。我们在所有的HTML表单和AJAX请求当中包含了一个特殊的token,而请求来自于其他的应用的时候,你就可以检测到。所有的这些选项在新创建的Rails2.0项目当中默认就是打开的状态,对于你升级到Rails2.0的项目要打开这一个选项也很容易,使用ActionController::Base.protect_from_forgery就可以了,详细的说明请看:ActionController::RequestForgeryProtection。

对于允许用户在应用当中提交HTML代码的情况,防止XSS攻击现在也变得更加简单了。TextHelper#sanitize方法从过滤黑名单变成了验证白名单。如果你已经使用了sanitize方法,你就会自动获得更好的保护。当然你也可以自行调整默认允许的HTML tag,请看TextHelper#sanitize获取详情。

最后,我们还添加了“ HTTP only cookies”支持,这一特性并不是所有的浏览器都支持,但是对于支持的浏览器你就可以派上用场了。


Action Pack: Exception handling

大多数常见的异常都可以统一处理,而不是每个需要单独的处理。通常情况下,你只需要覆盖rescue_action_in_public方法,来进行统一的异常处理即可。但是你也有可能需要使用自己的case语句来处理特定场合的异常。因此我们现在提供了一个类级别的宏叫做rescue_from,你可以使用它来声明针对某个特定的Action来捕获异常,例如:

Ruby代码 复制代码
  1. class PostsController < ApplicationController   
  2.   rescue_from User::NotAuthorized, :with => :deny_access  
  3.   
  4.   protected   
  5.     def deny_access   
  6.       ...   
  7.     end  
  8. end  
  class PostsController < ApplicationController
    rescue_from User::NotAuthorized, :with => :deny_access

    protected
      def deny_access
        ...
      end
  end


Action Pack: Cookie store sessions

Rails2.0默认的Session存储机制现在是基于Cookie的方案。Session也可以不必存储在服务器的文件系统或者数据库系统里面,而是以ruby hash的格式每次作为cookie发送到客户端浏览器来保持。这样做不单单会比传统的服务器端保存Session的方式要快一些,而且完全不需要维护。你不需要在服务器上面运行cron job任务来清理session文件,也不必担心因为你忘记清理session文件导致你的服务器/tmp分区下面因为塞满了50万的session文件,从而让你的服务器crash掉。

如果你能够遵循一些最佳实践,保持session最小化,例如只在session里面存放user_id和flash信息,那么这种session机制就会很棒。但是,如果你打算在session里面保存核弹发射代码的话,这一存储机制就不是一个好主意了。因为它们无法被加密(例如用户伪造is_admin=true),它们很容易被用户看到。如果对于你的应用程序来说,这是一个必须注意的问题,那么你就应该使用传统的session存储机制(但你首先应该先做一下调查)。

Action Pack: New request profiler

在一个真实的应用当中找出性能瓶颈是一个艰难的活,但有了我们新的request profiler,工作会变得简单很多。request profiler跟踪一个完整的执行脚本,报告执行结果,你可以像这样来使用它:

Ruby代码 复制代码
  1. $ cat login_session.rb   
  2. get_with_redirect '/'  
  3. say "GET / => #{path}"    
  4. post_with_redirect '/sessions':username => 'john':password => 'doe'  
  5. say "POST /sessions => #{path}"    
  6. $ ./script/performance/request -n 10 login_session.rb  
  $ cat login_session.rb
  get_with_redirect '/'
  say "GET / => #{path}" 
  post_with_redirect '/sessions', :username => 'john', :password => 'doe'
  say "POST /sessions => #{path}" 
  $ ./script/performance/request -n 10 login_session.rb


这样你就可以得到一份非常详尽的HTML和text格式的运行报告,每个步骤执行了多少时间,有了这个东西,你就可以很清楚的知道怎样优化你的应用程序了。

Action Pack: Miscellaneous

还有一个值得一提的是AtomFeedHelper。它可以让你更容易的使用增强的builder格式来创建RSS输出,例如:

Ruby代码 复制代码
  1. # index.atom.builder:   
  2. atom_feed do |feed|   
  3.   feed.title("My great blog!")   
  4.   feed.updated((@posts.first.created_at))   
  5.   
  6.   for post in @posts  
  7.     feed.entry(post) do |entry|   
  8.       entry.title(post.title)   
  9.       entry.content(post.body, :type => 'html')   
  10.   
  11.       entry.author do |author|   
  12.         author.name("DHH")   
  13.       end  
  14.     end  
  15.   end  
  16. end  
  # index.atom.builder:
  atom_feed do |feed|
    feed.title("My great blog!")
    feed.updated((@posts.first.created_at))

    for post in @posts
      feed.entry(post) do |entry|
        entry.title(post.title)
        entry.content(post.body, :type => 'html')

        entry.author do |author|
          author.name("DHH")
        end
      end
    end
  end


在Rails2.0里面,我们已经进行了大量的性能优化,因此对于helper的调用开销已经变得很小了,而且对于简单的命名路由,我们还使用了cache,让它们能够执行的更快。

最后我们把in_place_editor和autocomplete_for这两个helper从Rails框架当中挪出去,放到了Rails官方SVN的插件目录下面了。

Active Record: Performance

ActiveRecord进行了无数的bug修复和少量的调整,但是仍然有一些值得一提的亮点。我们添加了一个非常简单的查询缓存,它能够在同一个请求的过程当中记录相似的SQL调用,并且缓存查询结果。查询缓存对于那些很难用:include来解决的N+1次查询问题会非常有帮助。另外我们也彻底提高了fixtures的性能,对于大多数常规的测试套件,性能提高了50-100%。

Active Record: Sexy migrations

现在我们有一种新的migration文件中声明的格式。以前我们是这样写的:

Ruby代码 复制代码
  1. create_table :people do |t|   
  2.   t.column, "account_id",  :integer  
  3.   t.column, "first_name",  :string:null => false  
  4.   t.column, "last_name",   :string:null => false  
  5.   t.column, "description":text  
  6.   t.column, "created_at",  :datetime  
  7.   t.column, "updated_at",  :datetime  
  8. end  
create_table :people do |t|
  t.column, "account_id",  :integer
  t.column, "first_name",  :string, :null => false
  t.column, "last_name",   :string, :null => false
  t.column, "description", :text
  t.column, "created_at",  :datetime
  t.column, "updated_at",  :datetime
end


而现在,我们可以这样写:

Ruby代码 复制代码
  1. create_table :people do |t|   
  2.   t.integer :account_id  
  3.   t.string  :first_name:last_name:null => false  
  4.   t.text    :description  
  5.   t.timestamps   
  6. end  
create_table :people do |t|
  t.integer :account_id
  t.string  :first_name, :last_name, :null => false
  t.text    :description
  t.timestamps
end


Active Record: Foxy fixtures

近来fixtures功能受到了很多抨击,对于fixtures的批评主要集中在fixtures之间声明的依赖关系上。在fixtures里面通过声明id属性来作为主键,从而构造fixtures之间的关联关系是个郁闷的活。现在你可以通过这种方式声明和编写fixtures:

Ruby代码 复制代码
  1. # sellers.yml   
  2. shopify:   
  3.   name: Shopify   
  4.   
  5. # products.yml   
  6. pimp_cup:   
  7.   seller: shopify   
  8.   name: Pimp cup  
  # sellers.yml
  shopify:
    name: Shopify

  # products.yml
  pimp_cup:
    seller: shopify
    name: Pimp cup


如上面所示,不再需要定义id属性,通过id来关联fixtures了,你现在可以直接使用fixtures的名字来建立关联关系。

Active Record: XML in, JSON out

ActiveRecord支持XML的序列化已经有一段时间了。在Rails2.0当中,我们还添加了XML的反序列化功能,所以你现在可以这样用Person.new.from_xml(“David“) 来获取person对象。当然我们也添加了序列化到JSON格式的功能,它和XML序列化的支持是一样的,还可以支持关联关系的抓取,只需要写person.to_json就可以了。

Active Record: Shedding some weight

为了让ActiveRecord更加简洁和通用,我们把acts_as_list,acts_as_tree等acts_as_xxx功能挪出了Rails,放在了Rails官方的SVN插件里面。如果你需要用到诸如acts_as_list的话,那么你需要安装这个插件,你可以./script/plugin install acts_as_list 来安装,安装好以后,acts_as_list功能又回来了,用法没有任何区别。

更加激进一点的改动是我们把所有的商业数据库驱动全部挪到了外部的gem包里面。因此Rails2.0仅仅自带MySQL、SQLite和PostgreSQL数据库驱动。这三个数据库是我们更加积极测试和支持的数据库。当然,这并非意味着我们排斥商业数据库,我们只是希望它们能够在Rails发行版本之外保持自己独立的开发和发布计划。对于商业数据库来说,这其实是一件好事情,让厂商可以在基础版本上面添加更多的异常和处理机制,使它们工作的更好。

所有的商业数据库驱动现在都放在gems包里面,符合如下命名规则:activerecord-XYZ-adapter。所以如果你安装了activerecord-oracle-adapter包,那么这台机器上面所有的各种版本的Rails应用程序都可以访问Oracle数据库了,你却无需修改任何一行应用的代码。

这种方式对于新的数据库驱动来说在Rails社区也可以更加方便的获得支持。只要你把数据库驱动安装命名规范打包成为gem,用户就可以安装这个gem,立刻在Rails程序当中使用到它们了。

Active Record: with_scope with a dash of syntactic vinegar

ActiveRecord::Base.with_scope被劝阻使用以避免用户在controoler,特别是filter里面误用。现在我们鼓励用户仅仅在model里面使用这种格式,这也是当初我们设计这项功能的初衷和保持一个良好实践的需要。当然,这仅仅只是鼓励和劝阻,如果你在衡量得失之后,非要坚持在model之外使用with_scope的话,你尽管可以用这种方式来调用:.send(:with_scope)。

ActionWebService out, ActiveResource in

在SOAP和REST的争论当中,Rails选择坚定的站在REST这一边似乎不出人意料。如果你并没有集成其他异构系统需求的话,那么我们强烈劝阻你使用SOAP。作为很自然的选择,ActionWebService现在并不在Rails框架的依赖当中,gem包仍然保留,但是这是一个重要的信息,建议你尽量不用它。

与此同时,我们把新的ActiveResource包从beta版本升级挪入Rails框架之内。ActiveResource很像ActiveRecord,只不过面向的不是model,而是资源。它有和ActiveRecord非常相似的API,并且可以和基于资源的Rails应用良好的整合。例如,ActiveResource提供了一个vanilla scaffold,你可以参考。

ActiveSupport

ActiveSupport没有多少新东西,我们只是添加了大量新的方法,例如Array#rand可以随机取得集合的元素,Hash#except可以过滤掉不想要的key和其他大量的Date类型的扩展。另外单元测试增加了一个assert_difference的便利方法。简而言之,仅仅是bugfix和调整。

Action Mailer

Action Mailer有不少更新,除了一大堆bugfix之外,我们添加了一个选项可以注册可选的模板渲染机制,此外还给email的单元测试添加一套assert_emails,例如验证邮件投递的数量:
Ruby代码 复制代码
  1. assert_emails 1 do post :signup:name => ‘Jonathan’ end  
assert_emails 1 do post :signup, :name => ‘Jonathan’ end



Rails: The debugger is back

为了更好的整合调试器,我们对Rails框架整体进行了一系列的改进。我最得意之作就是调试器的断点功能回来了,这不仅仅只是一个类似irb dump那样的断点数据观测,而是一个真正的调试器。你可以单步前进、单步后退、列举当前位置等等。这完全得益于ruby-debug这个gem包,所以我们推荐你安装这个gem包,然后Rails新的调试器就可以工作了。

如果你想使用调试器,那么首先安装ruby-debug这个gem包,然后把“debugger”命令写在你的应用程序当中,接着用-debugger或者-u参数启动服务器,当代码执行到debugger命令的地方,你就可以在运行服务器的终端上面直接操纵应用了,完全不需要使用script/breakpointer或者其他的什么东西。当然你还可以在单元测试当中使用调试器。


Rails: Clean up your environment

在Rails2.0之前的版本,config/environment.rb当中塞满了各种各样的启动配置信息和代码。现在你可以把这些东西分门别类的放在独立的文件当中,然后把文件放在config/initializers目录下面,当Rails应用启动的时候,它们就会被自动的加载。新的Rails2.0应用自带了两个这样的例子,分别是inflections.rb(定义你自己的单复数规则)和mime_types.rb(定义你自己的扩展类型)。我们鼓励你把启动配置信息放在独立的文件里面,而不要去改动environment.rb文件。


Rails: Easier plugin order

现在我们开始把很多功能从Rails剥离出来放到插件里面去了,你也许有可能有一些其他依赖这些功能的插件。例如在你自己的acts_as_extra_cool_list插件被加载之前,需要首先加载acts_as_list插件,因为acts_as_extra_cool_list扩展了acts_as_list。

在Rails2.0之前,设定插件的加载次序需要你在config.plugins里面列举所有的插件。这种做法主要的问题是当你仅仅需要acts_as_list插件加载次序在前,而不关心其他插件加载次序的时候,未免需要多写太多东西。而现在你仅仅这样写就可以了:config.plugins = [ :acts_as_list, :all ]。


And hundreds upon hundreds of other improvements

上面我提到的这么多特性也仅仅只是Rails2.0的冰山一角。我们可以列举出来成千上万的bug修复、功能调优、新功能的添加。许许多多的热情的贡献者不知疲倦的在各个细节上面改进Rails框架,但是这些工作都是非常重要的。

我希望你能够不介意麻烦去阅读Rails的CHANGELOG,了解更多的Rails2.0的改进。


So how do I upgrade?

如果你希望升级到Rails2.0,那么你应该首先升级到Rails 1.2.6版本。它对于所有在Rails2.0当中被挪出去的功能给出了警告信息。如果你的应用程序在Rails 1.2.6上面良好的运行,并且没有任何警告信息,那么你就可以升级到Rails 2.0了。当然如果你用到了Rails的分页的话,你需要安装classic_pagination这个插件。如果你需要使用Oracle数据库,那么你需要安装activerecord-oracle-adapter这个gem包,诸如此类等等等等。
  • 引用

* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 [lifofifo]

For example:

ruby script/generate migration AddSomeStuffToCustomers first_name:string last_name:string

or

ruby script/generate migration RemoveSomeStuffFromCustomers first_name:string last_name:string

生成的代码分别如下
Ruby代码 复制代码
  1. class AddSomeStuffToCustomers < ActiveRecord::Migration   
  2.   def self.up   
  3.     add_column :customers:first_name:string  
  4.     add_column :customers:last_name:string  
  5.   end  
  6.   
  7.   def self.down   
  8.     remove_column :customers:last_name  
  9.     remove_column :customers:first_name  
  10.   end  
  11. end  
class AddSomeStuffToCustomers < ActiveRecord::Migration
  def self.up
    add_column :customers, :first_name, :string
    add_column :customers, :last_name, :string
  end

  def self.down
    remove_column :customers, :last_name
    remove_column :customers, :first_name
  end
end

Ruby代码 复制代码
  1. class RemoveSomeStuffFromCustomers < ActiveRecord::Migration   
  2.   def self.up   
  3.     remove_column :customers:first_name  
  4.     remove_column :customers:last_name  
  5.   end  
  6.   
  7.   def self.down   
  8.     add_column :customers:last_name:string  
  9.     add_column :customers:first_name:string  
  10.   end  
  11. end  
class RemoveSomeStuffFromCustomers < ActiveRecord::Migration
  def self.up
    remove_column :customers, :first_name
    remove_column :customers, :last_name
  end

  def self.down
    add_column :customers, :last_name, :string
    add_column :customers, :first_name, :string
  end
end
引用

*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of ch anges from 1.1.4 - 1.2.3]

* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 [evan]

比如安装file_column
Java代码 复制代码
  1. ./script/plugin install http://opensvn.csie.org/rails_file_column/plugins/file_column/trunk   
./script/plugin install http://opensvn.csie.org/rails_file_column/plugins/file_column/trunk 

原来会把file_column安装到vender/plugins/trunk目录下
但是现在rails会很聪明的把file_column放到 vender/plugins/file_column目录下

相应的代码是
Ruby代码 复制代码
  1. def guess_name(url)   
  2.     @name = File.basename(url)   
  3.      if @name == 'trunk' || @name.empty?   
  4.        @name = File.basename(File.dirname(url))   
  5.     end  
  6.  end  
 def guess_name(url)
     @name = File.basename(url)
      if @name == 'trunk' || @name.empty?
        @name = File.basename(File.dirname(url))
     end
  end
引用

(来自 http://weblog.rubyonrails.org/2007/12/7/rails-2-0-it-s-done
# ArthurGeek 于 12月7日 15:51:

更多关于sexy migration:

以前你要这样写:
Ruby代码 复制代码
  1. create_table :people do |t|   
  2.    t.column, “account_id”, :integer  
  3.    t.column, “first_name”, :string:null => false  
  4.    t.column, “last_name”, :string:null => false  
  5.    t.column, “description”, :text  
  6.    t.column, “created_at”, :datetime  
  7.    t.column, “updated_at”, :datetime  
  8. end  
  create_table :people do |t|
     t.column, “account_id”, :integer
     t.column, “first_name”, :string, :null => false
     t.column, “last_name”, :string, :null => false
     t.column, “description”, :text
     t.column, “created_at”, :datetime
     t.column, “updated_at”, :datetime
  end


现在你只需要这样写:
Ruby代码 复制代码
  1. create_table :people do |t|   
  2.    t.references :account  
  3.    t.string :first_name:last_name:null => false  
  4.    t.text :description  
  5.    t.timestamps   
  6. end  
  create_table :people do |t|
     t.references :account
     t.string :first_name, :last_name, :null => false
     t.text :description
     t.timestamps
  end


t.references :account也可以写成 t.belongs_to :account(和ActiveRecord::Base一样)


和ActiveRecord::Base的belongs_to一样,多态也同样支持。

请对比下面两个例子,体会polymorphic的用法
Ruby代码 复制代码
  1. create_table :taggings do |t|   
  2.   t.integer :tag_id:tagger_id:taggable_id  
  3.   t.string  :tagger_type  
  4.   t.string  :taggable_type:default => 'Photo'  
  5. end  
  create_table :taggings do |t|
    t.integer :tag_id, :tagger_id, :taggable_id
    t.string  :tagger_type
    t.string  :taggable_type, :default => 'Photo'
  end

=>
Ruby代码 复制代码
  1. create_table :taggings do |t|   
  2.   t.references :tag  
  3.   t.references :tagger:polymorphic => true  
  4.   t.references :taggable:polymorphic => { :default => 'Photo' }   
  5. end  
 本文转自: http://robbin.javaeye.com/blog/147397
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值