Rails渲染或redirect_to与PATCH请求

时间:2015-05-04 05:20:39

标签: ruby-on-rails ruby http

我遇到了PATCH请求的问题。

我希望PATCH "/activities/7/mans"update有些值 但如果更新后的值无效,那么我该如何将其重定向到:new

这是rails服务器日志

Started PATCH "/activities/7/mans" for 127.0.0.1 at 2015-05-04 12:55:58 +0800
Processing by MansController#new as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"Qnn/N9yWMtxAwA9N+br5r+mMvPdoY4fBJaI3sCYnObY=","activity_id"=>"7"}

当我在更新后使用render new时 我总是得到{GET} not {PATCH}

Started GET "/activities/7/mans" for 127.0.0.1 at 2015-05-04 12:58:56 +0800
Processing by MansController#show as HTML
Parameters: {"activity_id"=>"7"}

这里是route.rb设置

resources :activities do
  resources :mans, :only => [:index ,:create] do
    collection do
      patch :new
    end
  end
end

这是我的控制器动作

  def new
    @activity = Activity.find_by_id(params[:activity_id])
    @man= Man.new
  end

  def create
    @man = Man.new(man_params)
    if @man.age <20
      redirect_to :new
    end
  end

1 个答案:

答案 0 :(得分:0)

如果出现验证错误,通常不会重定向,而是立即回复某些HTML:

  def create
    @man = Man.new(man_params)
    if @man.save # validation for age < 20 should be in the model
      redirect_to my_redirect_path
    else
      render :new
    end
  end

与您在问题中未提供的update行动完全相同:

  def update
    @man = Man.find(man_params[:id])
    if @man.update_attributes(man_params) # validation for age < 20 should be in the model
      redirect_to my_redirect_path
    else
      render :edit
    end
  end

这样您就可以使用@man.errors在视图中打印任何验证错误。

为了实现这一目标,您应该在控制器中执行edit(当然还有update)操作并修改路由,如下所示(如果您不需要show并且destroy行动):

resources :activities do
  resources :mans, :except => [:show, :destroy]
end