4

Rails 项目:Project有很多Ticket

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

当更新票证并且验证失败时,我使用render :action => "edit".

但是,当这次编辑视图渲染时,路径变为/tickets/11/

这意味着我丢失了一些参数。我怎样才能保持原来的路径?

路线.rb:

  resources :projects do
    resources :tickets
  end
  resources :tickets

门票控制器.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
4

2 回答 2

1

您正在调用资源两次。如果您不想“丢失一些参数”,请删除第二个。

resources :projects do
  resources :tickets
end

但是,如果您也想要resources :tickets非嵌套,您可以将其限制为仅showindex以避免在创建和编辑时丢失一些参数。

resources :projects do
  resources :tickets
end
resources :tickets, :only => [:index, :show]

编辑- 我相信问题出在你的形式上。
确保你有两个对象:

form_for([@project, @ticket]) do |f| 

此外,您必须project在创建或更新ticket. 因此,您的newedit操作必须具有以下内容:

@project = Project.find(params[:project_id])
@ticket = @project.ticket.build

和相同的create行动:

@project = Project.find(params[:project_id])
@ticket = @project.ticket.build(params[:ticket])

edit2 - 你的更新操作应该是这样的:

@project = Project.find(params[:project_id])
@ticket = Ticket.find(params[:id])
if @ticket.update_attributes(params[:ticket])
...
于 2013-02-11T12:32:37.840 回答
1

看看http://guides.rubyonrails.org/routing.html#nested-resources。您应该能够使用嵌套路由助手从控制器重定向到嵌套资源,例如project_ticket_path(@project, @ticket).

于 2013-02-11T12:35:52.953 回答