ruby-on-rails – RoR:更新操作.错误时渲染路径

Rails项目:项目有很多Ticket.

编辑故障单的路径:/ projects / 12 / tickets / 11 / edit

更新故障单并验证失败时,我使用render:action => “编辑”.

但是,当编辑视图呈现此时,路径将更改为/ tickets / 11 /

这意味着我失去了一些参数.我怎样才能保留原始路径?

routes.rb中:

  resources :projects do
    resources :tickets
  end
  resources :tickets

tickets_controller.rb

  def new
    @ticket = Ticket.new
  end

  def create
    @ticket = Ticket.new(params[:ticket])
    @ticket.user_id = session[:user_id]

    respond_to do |format|
      if @ticket.save
        format.html { redirect_to project_path(@ticket.project), :notice => "Ticket was created." }
      else
        format.html { render :action => "new" }
      end
    end
  end

  def edit
    @ticket = Ticket.find(params[:id])
  end

  def update
    @ticket = Ticket.find(params[:id])
    respond_to do |format|
      if @ticket.update_attributes(params[:ticket])
        format.html { redirect_to project_ticket_path(@ticket.project, @ticket), :notice => "Ticket was updated." }
      else
        format.html { render :action => "edit" }
      end
    end
  end

最佳答案 看看
http://guides.rubyonrails.org/routing.html#nested-resources.

您应该能够使用嵌套路由助手从控制器重定向到嵌套资源,例如project_ticket_path(@ project,@ ticket).

点赞