Rails项目:Project
有很多Ticket
个。
修改故障单的路径:/projects/12/tickets/11/edit
更新故障单并验证失败时,我使用render :action => "edit"
。
但是,当编辑视图呈现此时间时,路径将更改为/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
答案 0 :(得分:1)
你要两次调用资源。如果您不想“丢失一些参数”,请删除第二个参数。
resources :projects do
resources :tickets
end
但是,如果您希望resources :tickets
非嵌套,则可以将其限制为仅show
和index
,以避免在创建和编辑时丢失某些参数。
resources :projects do
resources :tickets
end
resources :tickets, :only => [:index, :show]
编辑 - 我认为问题出在你的形式上 确保你有两个对象:
form_for([@project, @ticket]) do |f|
此外,在创建或更新project
之前,您必须找到ticket
。因此,您的new
和edit
操作必须具有以下内容:
@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])
...
答案 1 :(得分:1)
看看http://guides.rubyonrails.org/routing.html#nested-resources。
您应该能够使用嵌套路由助手(例如project_ticket_path(@project, @ticket)
)从控制器重定向到嵌套资源。