0

我正在使用将像这样对引导程序进行分页:

我的模型:

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

宝石文件:

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 %>

在 contacts/create.js.erb 中调用:

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

只要此部分已在 Contacts 控制器的上下文中呈现(例如 views/contacts/create.js.erb),will_paginate 生成的链接如下:

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

现在,我想在 customer/show.html.erb 中渲染这个部分,如下所示:

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

但是 will_paginate 返回的链接是特定于客户的,而不是特定于联系人的。显然,will_paginate 访问 self(即 CustomerController)来构建链接。

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

如何告诉 partial 或 will_paginate 如何处理呢?我是否误解了 MVC、路线或其他任何东西的概念?我是否以错误的方式使用模型之间的关联?

任何帮助表示赞赏!谢谢你。戈尔比

4

1 回答 1

1

我调试了 will_paginate 并检测到 self 作为“模板”传递:

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 请求来调用 Contacts 控制器的 index 方法,如下所示:

一、在customers/show.html.erb中:

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

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

二、在 assets/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'),当我单击页面时,新数据会异步加载。

戈尔比

于 2013-07-01T15:34:30.543 回答