2007-08-01

Rails宝典之第三十五式: 自定义REST动作

关键字: Rails custom REST action
REST将我们的controller限制到7个actions(index/show/new/create/edit/update/desctroy)
这次我们就来看看怎样添加自定义的actions
class TasksController < ApplicationController
  def idnex...

  def show...

  def new...

  def create...

  def edit...

  def update...

  def destroy...

  def complete
    @task = Task.find(params[:id])
    @task.update_attribute :completed_at, Time.now
    flash[:notice] = "marked task as complete"
    redirect_to completed_tasks_path
  end

  def completed
    @tasks = Task.find(:all, :conditions => 'completed_at IS NOT NULL')
  end
end

我们创建了两个方法,我们需要修改routes.rb:
map.resources :tasks, :collection => { :completed => :get }, :member => { :complete => :put}

现在我们可以访问http://localhost:3000/tasks;completed了
我们来看看页面中怎样写该链接:
<%= link_to "Mark as complete", complete_task_path(task), :method => :put %>
<%= link_to "Completed Tasks", completed_tasks_path %>
评论
ziyoujiedao 2008-01-24
OK,明白,谢谢hideto
hideto 2008-01-23
不是不可以带参数,而是不带id,但可以带别的参数啊
close_movie_infos_path(:a => 1, :b => 2)生成的url -》/movie_infos/close?a=1&b=2
close_movie_info_path(:id => @movie_info, :a => 1, :b => 2)生成的url -》/movie_info/1/close?a=1&b=2
ziyoujiedao 2008-01-23
哦,大概明白了,那写在collection中的话,close_movie_infos_path不可以带参数了吧 例如close_movie_infos_path(movie_info)
hideto 2008-01-22
rake routes
看一下生成的named routes的方法名就知道了,应该为close_movie_infos_path

因为你是定义在:collection中而不是:member中,前者生成的routes为复数,后者则为单数
ziyoujiedao 2008-01-22
多个自定义action用GET方式请求,怎么写?
:collection => { :query => :get,:close => :get}可以这样写吗?
map.resources :movie_infos, :collection => { :close => :get}这样时,close_movie_info_path这样写出错
发表评论

您还没有登录,请登录后发表评论

hideto
搜索本博客
我的相册
A6bdc31c-c66e-468e-961e-9cc721e82adc-thumb
screenshot
共 1 张
存档
最新评论