带url params的render_to_string

时间:2015-08-07 13:44:19

标签: ruby-on-rails actioncontroller

我有一个sidekiq工作者,它应该呈现一个文件并保存它。

在通过render_to_string的渲染过程中,我传递了一堆实例变量和变量,如current_user,它可以正常工作。

但要渲染我的观点,我还需要像params[:action]这样的网址参数。如何使用render_to_string

将它们传递给视图
# SpecialWorker.rb
class ConclusionRenderingWorker < AbstractController::Base
  include Sidekiq::Worker
  ac = ActionController::Base.new()

  data = ac.render_to_string(:template => "my/rendering_view.html.erb",
    layout: false,
    :locals => {
         :@instance_variable1 => instance_variable1,
         :params => [action: 'myaction']
    }
)

# my/rendering_view.html.erb
  <% unless params[:action] == 'dashboard' %>
   Blah
  <% else %>
   Blubb
  <% end %>

我得到的错误:

2015-08-07T13:20:20.103Z 54344 TID-oxuugdhn4 WARN: "class"=>"ConclusionRenderingWorker", "args"=>[1, 18], "retry"=>true, "queue"=>"default", "jid"=>"1c97d91dc5db162ecd225418", enqueued_at"=>1438953617.792468, "error_message"=>"undefined method `parameters' for nil:NilClass", error_class"=>"ActionView::Template::Error",  failed_at"=>1438953620.102505, "retry_count"=>0}
2015-08-07T13:20:20.103Z 54344 TID-oxuugdhn4 WARN: undefined method `parameters' for nil:NilClass

不起作用:

:params => [action: 'conclusion']

:@params => [action: 'conclusion']

我也遇到了所有路径的问题:

<%= url_for :host =>'http://localhost:3000/', only_path: true, controller: API::V1::CommentsController, action: :load_more_comments %>
...
.. 
.

抛出

undefined method `host' for nil:NilClass /Users/jan/.rbenv/versions/2.0.0-p643/lib/ruby/gems/2.0.0/gems/actionpack-3.2.14/lib/action_controller/metal/url_for.rb:30:in `url_options'

/Users/jan/.rbenv/versions/2.0.0-p643/lib/ruby/gems/2.0.0/gems/actionpack-3.2.14/lib/action_view/helpers/url_helper.rb:37:in `url_options'

/Users/jan/.rbenv/versions/2.0.0-p643/lib/ruby/gems/2.0.0/gems/actionpack-3.2.14/lib/action_dispatch/routing/url_for.rb:148:in `url_for'

/Users/jan/.rbenv/versions/2.0.0-p643/lib/ruby/gems/2.0.0/gems/actionpack-3.2.14/lib/action_view/helpers/url_helper.rb:107:in `url_for'

1 个答案:

答案 0 :(得分:0)

:params => [action: 'myaction']是一个里面有哈希的列表,对于params [:action]来说,你需要做:params => { action: 'myaction' }

<强> UPDATE1:

一个名为params的变量似乎在rails内部得到特殊处理。您可以执行以下操作

# SpecialWorker.rb
class ConclusionRenderingWorker < AbstractController::Base
  include Sidekiq::Worker
  ac = ActionController::Base.new()

  data = ac.render_to_string(:template => "my/rendering_view.html.erb",
    layout: false,
    :locals => {
         :@instance_variable1 => instance_variable1,
         :action => 'myaction'
    }
)

# my/rendering_view.html.erb
<% unless action == 'dashboard' %>
  Blah
<% else %>
  Blubb
<% end %>

因此,请避免使用params,而只是将值作为局部变量传递给模板。