我收到此错误,我尝试添加redirect_to()并返回我的access_doc_or_redirect()方法,但没有运气。有什么建议吗?
def access_doc_or_redirect(doc_id, msg)
doc = Document.find(params[:id])
if doc.user_access?(current_user)
@document = doc
else
flash[:alert] = msg
redirect_to root_url and return
end
end
def get
access_doc_or_redirect(params[:id], "Sorry, no document view access.")
redirect_to @document.file.url
end
access_doc_or_redirect(params [:id],"抱歉,没有文档视图访问" AbstractController :: DoubleRenderError:在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,每次操作最多一次。另请注意,重定向和渲染都不会终止操作的执行,因此如果要在重定向后退出操作,则需要执行类似" redirect_to(...)的操作并返回"。
答案 0 :(得分:1)
AbstractController :: DoubleRenderError:在此操作中多次调用渲染和/或重定向。
错误是自我描述性的,您在操作中多次调用渲染或重定向。让我们看看你的方法:
def access_doc_or_redirect(doc_id, msg)
doc = Document.find(params[:id])
if doc.user_access?(current_user)
@document = doc
#this block will run fine and return @document to get method
else
flash[:alert] = msg
redirect_to root_url and return
#this block is giving you trouble because you are redirecting to root url and then control goes back to your get method where you are using redirect again and hence double render error
end
end
<强> FIX:强>
如果您将其用作过滤器,则可以修复错误:
def get
#i think this is your main method so you should use redirect or render inside this method only
#instance variables set inside access_doc_or_redirect will automatically be available inside this method
if @document
redirect_to @document.file.url
else
flash[:alert] = "Sorry, no document view access."
redirect_to root_url
end
end
def access_doc_or_redirect
@doc = Document.find(params[:id])
if @doc.user_access?(current_user)
@document = doc
end
end