2014-10-19 59 views
0

我想通過ajax調用更新索引頁。我遇到的唯一問題是返回的will_paginate鏈接具有url的.js擴展名。渲染will_paginate鏈接,如果通過html請求,當通過ajax請求時

這是我的coffeescript,使請求。

onSearchBoxChanged :() -> 
    console.log "search box changed" 
    console.log @view.getSearchBoxContents() 
    jQuery.getScript('/users.js?search=' + @view.getSearchBoxContents()) 

在用戶控制器中,我對html和javascript都做出了迴應。

respond_to :html, :js 

我也有局部的will_paginate鏈接(在_paginate.html.erb文件)

<%= will_paginate %> 

這裏是我的index.js.coffee文件

console.log "back from server " 
console.log '<%= escape_javascript(render(@users)) %>' 
userList = '<%= escape_javascript(render(@users)) %>' 
console.log '<%= escape_javascript(render("paginate")) %>' 
paginate = '<%= escape_javascript(render("paginate")) %>' 
jQuery.publish('new_user_list_from_server', [ userList, paginate ]) 

這裏是在控制檯上打印的鏈接

<div class="pagination"><ul><li class="prev previous_page disabled"><a href="#">&#8592; Previous</a></li> <li class="active"><a rel="start" href="/users.js?_=1413756082270&amp;page=1&amp;search=j">1</a></li> <li><a rel="next" href="/users.js?_=1413756082270&amp;page=2&amp;search=j">2</a></li> <li class="next next_page "><a rel="next" href="/users.js?_=1413756082270&amp;page=2&amp;search=j">Next &#8594;</a></li></ul></div> 

我可以只替換所有的/users.js?與/用戶?,但它似乎應該有一個不那麼「黑客」的方式來做到這一點。

任何想法?

回答

0

我有一個類似但不完全相同的問題,我用自定義渲染器解決了這個問題。這是一個少hacky,但不幸的是我需要添加的代碼是在超級方法的中間,所以沒有簡單的方法來使用「超級」。此代碼位於app/helpers/pagination_helper.rb中。它會使用原始副本覆蓋呈現器的鏈接方法,並在中間插入一些新代碼,因此請注意,它易受到修訂will_paginate代碼自身引入的錯誤的影響。

module PaginationHelper 
    class Renderer < WillPaginate::ActionView::LinkRenderer 
    protected 
    def link(text, target, attributes = {}) 
     if target.is_a? Fixnum 
     attributes[:rel] = rel_value(target) 
     target = url(target) 
     end 

     # New code here: 
     if @options[:path].present? 
     parts = target.split "?" 
     parts.shift 
     parts.unshift @options[:path] 
     target = parts.join "?" 
     end 
     # End of new code 

     attributes[:href] = target 
     tag(:a, text, attributes) 
    end 
    end 
end 

然後在視圖指定自定義渲染器和覆蓋路徑:

<%= will_paginate @my_models, path: my_models_path, renderer: PaginationHelper::Renderer %>