教程

引言

你一定是已经听说了强大的活动脚手架插件,才会访问到这里来。想试试看?很简单,只需要3步。

第1步:首先安装这个插件的最新版本:

./script/plugin install http://activescaffold.googlecode.com/svn/tags/active_scaffold

或者你可以从trunk安装( http://activescaffold.googlecode.com/svn/trunk )这样就可以与核心团队开发的最新功能与时俱进。但是,trunk版本可能非常不稳定(因为还没有充分测试),所以不予推荐.

第2步:在布局文件(layout)中加入:

<%= javascript_include_tag :defaults %><%= active_scaffold_includes %>

第3步:在控制器(controller)中加入:

active_scaffold :<your_model_name>

…比如:

class UserController < ApplicationController
  active_scaffold :user
end

附加说明:请确保在你的项目里没有装过AjaxScaffold

没了,就这些!

介绍得太简单了?

好吧,再介绍一下以上步骤所影响的上下文。

在布局文件中的<head>元素中应该是这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
 <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
 <title>Generic ActiveScaffold Layout</title>
<%= javascript_include_tag :defaults %>
 <%= active_scaffold_includes %>
</head>
<body>
<%= yield  %>
</body>
</html>

然后控制器应该是这样:

class CompaniesController < ApplicationController
  layout "admin"
  active_scaffold :company
end

如果你的控制器与模型名称相同,甚至可以这样简写:

class CompaniesController < ApplicationController
  layout "admin"
  active_scaffold
end

这样是不是好懂多了?

请多一些灵活性

首先,介绍一下全局配置代码块(block)。你可能已经注意到了,活动脚手架把数据表中所有的东西都包含进来了。但是在配置代码块中写一行代码,就可以滤掉一些字段。在ApplicationController中加入:

class ApplicationController < ActionController::Base
  ActiveScaffold.set_defaults do |config|
    config.ignore_columns.add [:created_at, :updated_at, :lock_version]
  end
end

再让我们看看本地配置代码块。这个代码块放在与模型对应的控制器中。比如,Company模型的配置代码块放在CompaniesController中。ActiveScaffold规定一个控制器中只配置一个模型。再看这个例子:

class Admin::CompaniesController < ApplicationController
  active_scaffold :company do |config|
    config.label = "Customers"
    config.columns = [:name, :phone, :company_type, :comments]
    list.columns.exclude :comments
    list.sorting = {:name => 'ASC'}
    columns[:phone].label = "电话"
    columns[:phone].description = "(格式:###-###-####)"
  end
end

你希望有更多灵活性,现在你看到了。你可以修改ActiveScaffold的标签(label),决定包含那些字段,并控制这些字段的所属动作,定义缺省排序,为每个字段指定标签和描述。

生成scaffold_resources

如果正在创建一个新的应用程序,希望使用控制器资源和REST式的路径,那么你要了解一下怎样用ActiveScaffold调整 script/generate scaffold_resources 的结果。运行完这个生成器之后,你需要打开生成的控制器,清空内建的Rails脚手架,替换成 active_scaffold :my_model 。然后,打开config/routes.rb编辑那行新的map.resources加上一个 :active_scaffold => true 参数。

延伸阅读