Respond_to and redirect in the same action in Rail

2019-07-30 02:03发布

In the Update action of Rails controllers usually there is code that looks like this:

def update
  @book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
    redirect_to(@book)
  else
    render :edit
  end
end

In the else case, this will render the edit template. But what if I wanted to use a respond_to, exactly the same way that I have in the edit action, as:

def update
  @book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
    redirect_to(@book)
  else
    respond_to do |format|
      format.html  # edit.html.erb
      format.json  { render :json => @team }
    end
  end
end

So, if the Update fails, be sure you are returning a json or html depending on the requested format. Does that makes sense? If so, how would you avoid the error: "Render and/or redirect were called multiple times in this action"

1条回答
贪生不怕死
2楼-- · 2019-07-30 02:29

Makes sense to me. The answer should be simple, just return after redirect_to.

def update
  @book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
    redirect_to(@book)
    return
  else
    respond_to do |format|
      format.html  # edit.html.erb
      format.json  { render :json => @team }
    end
  end
end

Not sure exactly how you're rendering multiple times, but assuming you are, a well-placed return should tell RAILS to stop processing any further renders after redirecting. If that's all true, it's likely that there's an after_filter interfering from somewhere.

查看更多
登录 后发表回答