2013-07-01 31 views
0

我使用的是將分頁自舉這樣的:的Rails:控制器(個體經營)的背景下產生的will_paginate鏈接

我的模型:

class Customer < ActiveRecord::Base 

    attr_accessible :city, :country, :name, :street, :zip 

    //... more code 

    has_many :contacts, :dependent => :destroy, :autosave => true 

end 


class Contact < ActiveRecord::Base 
    attr_accessible :name, :notice, :phone 

    //... more code 

    belongs_to :customer 
end 

的Gemfile:

gem "will_paginate-bootstrap" 

部分它能夠在contacts/_pageable_contacts.html.erb中生成分頁輸出:

<% 
    contacts = contacts.to_a.paginate(:page => params[:page] || 1, :per_page => 5) 
%> 
<%= render(:partial => 'contacts/contacts', :locals => {:contacts => contacts})%> 
<%= will_paginate contacts, renderer: BootstrapPagination::Rails, remote: true %> 

調用內部觸點/ create.js.erb:

<% 
all = @contact.customer.contacts 
%> 
<%= render :partial => "contacts/pageable_contacts", :locals => { :contacts => all } %> 

通過will_paginate產生的鏈接如只要該部分已經在聯繫人控制器的上下文中被渲染如下(例如意見/聯繫人/ create.js.erb):

customers/3/contacts?page=1 
customers/3/contacts?page=2 

現在,我想使這個部分裏面的客戶/ show.html.erb這樣的:

<%= render :partial => 'contacts/pageable_contacts', :object => @customer.contacts, :as => :contacts %> 

但是,will_paginate返回的鏈接是客戶特定的而不是特定的聯繫人。顯然,will_paginate的訪問自我(即CustomerController)來構建鏈接。

customers/3?page=1 
customers/3?page=2 

我該如何告訴部分或will_paginate如何處理它?我誤解了MVC的概念,路線或其他嗎?我是否以錯誤的方式使用模型之間的關聯?

任何幫助表示讚賞! 謝謝你。 golbie

回答

1

我調試will_paginate和檢測,自我作爲「模板」通過:

def will_paginate(collection, options = {}) 
    # early exit if there is nothing to render 
    return nil unless collection.total_pages > 1 

    options = WillPaginate::ViewHelpers.pagination_options.merge(options) 

    #............. more code 

    # render HTML for pagination 
    renderer.prepare collection, options, self #####<====== self is Customers Controller 
    renderer.to_html 
end 

我找到了一個解決辦法:不要使用「渲染」機制,我使用一個Ajax請求調用索引聯繫控制器這樣的方法:

I.在客戶/ show.html.erb:

<div id="contacts"> 
</div> 

<%= javascript_tag "ProtoSupport.fetchCustomersContacts('#{customer_contacts_path(@customer)}');" %> 
<%= javascript_tag 'ProtoSupport.addAsyncPagination();' %> 

II。在資產/ JavaScript的/ application.js中在ProtoSupport這兩個新方法:

 fetchCustomersContacts : function(path) { 
      $.getScript(path); 

     }, 
     addAsyncPagination : function() { 
      $(function() { 
       $(".pagination a").on("click", function() { 
        if($(this).attr('href') == '#') return false; 
        $(".pagination").html("Page is loading..."); 
        $.getScript(this.href); 
        return false; 
       }); 
      }); 
     } 

的鏈接是正確的,現在(例如'http://localhost:3000/customers/3/contacts?page=16'),當我點擊頁面上的新數據異步加載。

golbie

相關問題