从控制器动态更改视图 - Rails 中带有线程的进度条
我的控制器中有一个耗时任务,我想在我的视图中触发一个简单的进度条/进度状态。
在我的控制器中,我有一些东西,比如
threads = []
total.times do |x|
Thread.new {
the_time_taking_task(x)
#Something here to trigger the progressbar in the view
}
end
threads.each { |aThread| aThread.join }
render :action => 'some_action'
我无法将渲染放在那里,因为它会引发双重渲染错误。 我尝试在那里放置渲染并返回,但出现“返回无法跨线程跳转
”错误
我正在尝试渲染,因为这似乎是我的控制器可以与视图对话的唯一方式。我的方法是错误的吗?
想要在视图中使用像这样简单的东西,通过该调用应用进度条宽度,
<div style="width: <%= (percent_val)%>px; ">
请提出建议。
I have a time taking task in my controller for which I want to trigger a simple progress bar/progress status in my view.
In my controller I have something like
threads = []
total.times do |x|
Thread.new {
the_time_taking_task(x)
#Something here to trigger the progressbar in the view
}
end
threads.each { |aThread| aThread.join }
render :action => 'some_action'
I can't put a render in there because it throws a double render error.
I tried putting a render and return there and I got 'return can't jump across threads
' error
I am trying render as it seems to be the only way my controller can talk to view. Is my approach wrong ?
Would want something simple like this in the view which applies the progress bar width through that call
<div style="width: <%= (percent_val)%>px; ">
Please advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是一个错误的方法。
Web 是无状态的,您无法阻止渲染视图的进程并通过另一个请求获取它。
好方法是:
1)生成队列任务而不是线程。您可以使用delayed_job、resque 或队列系统,例如rabbitMQ 或beanstalkD
2) 添加控制器来检查队列中的进程是否结束以及进度如何。在里面,您输入队列 ID 并检查是否结束并返回进度百分比。
最简单的方法是通过 Ajax 来实现。
Yes it's a wrong approach.
The Web is stateless, and you can't block a process to render view and get it after by another request.
The good way is :
1) Generate a queue tasking instead of your thread. You can use delayed_job, resque or queue system, like rabbitMQ or beanstalkD
2) Add a controller to check if the process in your queue is end and how is progress. Inside, you put the queue id and check if is end or not and return the progress percent.
The easiest way is do that by Ajax.
是的,你的做法是错误的。
shingara 很好地解释了这一点。
我为您提供一个稍微具体的解决方案。
为了获得您想要的效果,您基本上需要以下步骤:
你完成了! :D
Yes, your approach is wrong.
shingara explains this well.
I'm offering a slightly more concrete solution for you.
To get the effect you want, you basically need the following steps:
You're done! :D