Rails:will_paginate在控制器上下文中生成的链接(self)

时间:2013-07-01 13:55:01

标签: ruby-on-rails controller hyperlink will-paginate

我正在使用像这样的paginate bootstrap:

我的模特:

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

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

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

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

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

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

任何帮助表示赞赏! 谢谢你。 golbie

1 个答案:

答案 0 :(得分: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控制器的索引方法,如下所示:

予。在customers / show.html.erb中:

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

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

II。在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'),当我点击页面时,新数据会异步加载。

golbie