`
JasonChi
  • 浏览: 92040 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

rails的REST特性简记(转)

 
阅读更多
1.关于REST的URL的详细讨论,参见《RESTful Rails development》文档,这里有中文翻译。Path-Methods对照表:

HTTP verb Path action named helper
GET /photos index images_path
GET /photos/new new new_image_path
POST /photos create images_path
GET /photos/1 show image_path
GET /photos/1/edit edit edit_image_path
PUT /photos/1 update image_path
DELETE /photos/1 destroy image_path

2.在Controller和View中新增加了一些helper方法,URL路由的设置来自config目录下的routes.rb中的一行代码:
map.resources :projects

这行代码将自动产生用于Controller的系列url方法和用于View的系列Path方法,对照表
路由             产生的Helper
-----------------------------------------------------------
projects       projects_url, projects_path
project        project_url(id), project_path(id)
new_project    new_project_url, new_project_path
edit_project   edit_project_url(id), edit_project_path(id)

3.路由的定制,通过下面的选项来定制符合个人需要的路由规则:
:controller.   设置使用的Controller.
:path_prefix.  URL前缀.
:name_prefix.  用于设置产生的helper方法的前缀
:singular. To name the singular name to be used for the member route.

4.Nested Resource(嵌套资源乎?),当rails采用REST架构时如何处理过去的Model之间的关联关系,比如1:N?比如以文档中的例子来说明,一个project可能有多个iteration,典型的一对多关系,我们在产生Model后,与传统rails一样,设置关联关系:
class Project  @iterations.to_xml }
  end
end

3)相应的iteration的Controller和View的Url和Path等helper都增加了一个参数,他们的第一个参数都将是project_id,比如



同样,所有form_for指向的url的helper也都增加了这个参数。总结一句话,被嵌套类(这里的iteration)的所有helper都增加一个参数并且是第一个参数——外包类(这里的project)的id

5.自定义action,对于不能归结为crud操作的action,我们需要自己定义action,已经说过,REST把所有的远程调用抽象为对远程资源的CRUD操作,非CRUD操作应当转化或者说抽象成CRUD操作,比如对于project可以有一个关闭操作close,我们可以把它理解成一个http POST请求去修改project的closed字段为true,这样一来这个操作也可以当作CRUD操作了。需要做的是在routes.rb增加一行:
map.resources :projects, :member => { :close => :post }

定义close action是POST方法,在Controller增加close方法:
def close
   respond_to do |format|
      if Project.find(params[:id]).update_attribute(:closed, true)
       flash[:notice] = "Project was successfully closed."
       format.html { redirect_to projects_path }
       format.xml { head[img]/images/smiles/icon_surprised.gif" alt="[/img]k }
     else
       flash[:notice] = "Error while closing project."
       format.html { redirect_to projects_path }
       format.xml { head 500 }
     end
   end
end

你可以通过http://localhost:3000/project/:project_id;close来调用此方法,请注意,POST的方法需要通过Form来实现,因此我们使用button_to:


自定义action不仅仅可以使用REST风格,传统的controller/action/id的方式仍然可以使用,注意下routes.rb的最后两行即可。

6.自定义格式,rails支持的格式有:
respond_to do |wants|
  wants.text
  wants.html
  wants.js
  wants.ics
  wants.xml
  wants.rss
  wants.atom
  wants.yaml
end

自定义格式需要在config/environment.rb中增加一行进行注册,比如pdf格式?
Mime::Type.register "application/pdf", :pdf
当然,你需要实现自己的to_pdf方法了

7.在rails1.2中使用AJAX与过去没有什么不同,仅仅是页面调用的URL全部改成新增加的那些Path helper

8.激动人心的ActiveResource,目前还未正式加入rails1.2,值的期待,简单来说就是就是通过这个库你将可以使用所有按照REST实现的web APIS,操作远程的资源将和操作本地的ActiveRecord一样。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics