Rails 4通过escape_javascript渲染部分集合

时间:2014-10-27 16:02:09

标签: ruby-on-rails ajax partials kaminari

我有以下代码,我想通过javascript(Kaminari通过AJAX分页)呈现:

<div id="paginator-jobs-top" class="text-center">
  <%= paginate @jobs, remote: true,
                       theme: 'twitter-bootstrap-3',
                  param_name: 'jobs',
                      params: { tab: 'jobs' },
            pagination_class: 'pagination-small pagination-centered' %>
</div>
<div id="jobs">
  <%= render partial: 'jobs/job_panel', collection: @jobs, as: :job %>
</div>
<div id="paginator-jobs-bottom" class="text-center">
  <%= paginate @jobs, remote: true,
                       theme: 'twitter-bootstrap-3',
                  param_name: 'jobs',
                      params: { tab: 'jobs' },
            pagination_class: 'pagination-small pagination-centered' %>
</div>

我正在尝试使用这个js.erb代码,但它根本不起作用:

$('#paginator-jobs-top').html('<%= escape_javascript(paginate(@jobs,
                                                          remote: true, 
                                                           theme: "twitter-bootstrap-3",            
                                                          param_name: "jobs",   
                                                              params: { tab: "jobs" },
                 pagination_class: "pagination-small pagination-centered").to_s) %>');

$('#jobs').html('<%= escape_javascript(render partial: "jobs/job_panel", 
                                           collection: @jobs, 
                                                   as: :job) %>');

我尝试了其他变体,但没有一个有效。如果有人知道如何用js.erb方法渲染上面的代码,我很乐意听到!

我从上面得到的错误是:

ArgumentError - wrong number of arguments (0 for 1)

当我在js.erb片段(没有',job:j')中使用稍微不同的行尝试时,我得到:

NameError - undefined local variable or method `job' for #<#<Class:0x

****基于Blelump的建议,我将我的代码更改为***

<div id="jobs">
  <%= render partial: "jobs/job_panel", collection: @jobs, as: :job %>
</div>

在没有AJAX的情况下效果很好(这实际上是在Rails中渲染集合部分的正确方法,我之前的错误)。但是,当我将js.erb文件调整为此时,我仍然会收到错误:

$('#jobs').html('<%= escape_javascript(render partial: "jobs/job_panel", 
                                           collection: @jobs, 
                                                   as: :job) %>');

错误来自Kaminari:

NoMethodError - undefined method `current_page' for nil:NilClass:
  kaminari (0.16.1) lib/kaminari/helpers/action_view_extension.rb:18:in `paginate'

1 个答案:

答案 0 :(得分:1)

尝试:

$('#jobs').html('<%=raw @jobs.collect {|j| escape_javascript(render :partial => "jobs/job_panel", :locals => {:job => j}) }.join("") %>');

或更简单,渲染集合

$('#jobs').html('<%=raw escape_javascript(render :partial => "jobs/job_panel", :collection => @jobs, :as => :job) %>');