will_pagate gem으로 아약스 페이지화를 구현하는 방법
사용 중will_paginate
내 안의 보석ROR
페이지로 레코드를 표시하는 프로젝트입니다.
전체 페이지를 다시 로드하지 않고 다음 페이지를 로드합니다.ajax
.
인터넷에서 몇 가지 예시를 찾았지만 저에게는 통하지 않습니다.
어떻게 하는 거지?
다음 내용을 사용하여 새 도우미(예: app/helperers/will_paginate_helper.rb)를 만듭니다.
module WillPaginateHelper
class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]['_'] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
@template.link_to(target, attributes.merge(remote: true)) do
text.to_s.html_safe
end
end
end
def js_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
end
end
그런 다음 이 태그를 Ajax 페이지에 사용합니다.
<%= js_will_paginate @recipes %>
페이지화 링크에는 URL의 기존 매개 변수가 포함됩니다. 아래와 같이 이러한 매개 변수를 제외할 수 있습니다.다음은 표준 페이지 기능입니다.
<%= js_will_paginate @recipes, :params => { :my_excluded_param => nil } %>
그게 당신의 문제를 해결하길 바랍니다.
업데이트 1: 이 솔루션을 게시한 원래 질문에 이 솔루션의 작동 방식에 대한 설명을 추가되었습니다.
업데이트 2: Rails 4를 remote: true links와 호환되도록 만들고 도우미 메소드의 이름을 js_will_pagate로 변경했습니다.
제품 페이지를 작성하려면 다음을 사용해 보십시오.
app/controller/products_controller.dll
def index
@products = Product.paginate(page: params[:page], per_page: 10)
end
보기/제품/index.dll.erb
<div class = "sort_paginate_ajax"><%= render 'products' %></div>
보기/제품/_products.vmdk.erb
<% @products.each do |product| %>
# your code
<% end %>
<%= will_paginate @products %>
보기/제품/index.js.erb
$('.sort_paginate_ajax').html("<%= escape_javascript(render("products"))%>")
자산/스크립트/애플리케이션.js
$(function() {
$(".sort_paginate_ajax th a, .sort_paginate_ajax .pagination a").on("click", function(){
$.getScript(this.href);
return false;
});
});
그래서 먼저 모든 제품에 대해 paginate 메소드를 호출합니다. 여기서 오프셋은 다음에 따라 설정됩니다.params[:page]
그리고 한계는 다음과 같이 정해질 것입니다.per_page
옵션들.또한 우리는 렌더링 중입니다.products
다른 페이지를 열 때마다 렌더링되는 부분입니다.
부분적인 방문으로@products
당신이 원하는 것, 그리고 나서.will_paginate
메서드가 적용됨@products
그것은 또한 창조합니다.params[:page]
컨트롤러에서 사용됩니다.
이제 Ajax 요청에 대한 응답으로 컨텐츠 렌더링div
수업하기sort_paginate_ajax
우리가 만든 부분으로.
또한 모든 문서 로드 캡처 스크립트에 대해 Ajax 요청을 하기 위해a
의 태그div.sort_paginate_ajax
거짓으로 반환합니다.
이제 Ajax 요청과 함께 페이지가 호출됩니다.
이것이 당신에게 도움이 되길 바랍니다.
이전 답변에 추가합니다.
코드 문자열:
$(".sort_paginate_ajax th a, .sort_paginate_ajax .pagination a").on("click", function(){
문자열로 대체:
$(".sort_paginate_ajax").on("click", ".pagination a", function(){
온클릭 이벤트는 이미 존재하는 요소에만 적용됩니다.따라서 새 모양 링크의 경우 상위 ".sort_paginate_ajax"에서 하위 ".paginationa"로 위임 클릭 이벤트가 필요합니다.
JQuery를 사용할 수 있습니다.
컨트롤러:
def index
@posts = Post.paginate(:page => params[:page])
respond_to do |format|
format.html
format.js
end
end
그런 다음 index.html.erb:
<div id="post-content", posts: @posts >
<%= j render 'post_content' %>
</div>
부분적으로 '_post_content.html.erb'인 경우:
<%= will_paginate @posts %>
<% @posts.each do |post| %>
<p><%= post.content %></p>
<% end %>
페이지 번호js:
$(document).ready(function() {
$('.pagination > a').attr('data-remote', 'true');
});
index.js.erb:
$('#post-content').html("<%= j render 'post_content' %>")
다음을 추가해야 합니다.
$('.pagination > a').attr('data-remote', 'true');
JS 템플릿(index.js.erb)에 다시 추가되므로 Ajax가 실행될 때 data-remote 링크가 다시 설정됩니다.
저는 피에르의 답변에 대해 자세히 설명하고 싶습니다.
will_paginate_materialize와 함께 materialize sas를 사용하는 경우 페이지 링크를 스타일화할 수 있는 이니셜라이저가 제공됩니다.
gem 'will_paginate', '~> 3.1.0'
gem 'will_paginate-materialize', git: 'https://github.com/mldoscar/will_paginate-materialize', branch: 'master'
그래서 will_paginate_materialize initializer가 제공하는 링크에서 원격 true가 작동하도록 하기 위해 다음을 수행했습니다.
will_continuate_continuate.dll
module WillPaginateHelper
class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
end
def js_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer =>WillPaginateHelper::WillPaginateJSLinkRenderer))
end
end
will paginate materialize initializer를 다음과 같이 변경했습니다.
will_continuate_materialize.dll
MaterializePagination::MaterializeRenderer.module_eval do
def page_number(page)
classes = ['waves-effect', ('active' if page == current_page)].join(' ')
tag :li, link(page, page, :rel => rel_value(page)), class: classes
end
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]['_'] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
@template.link_to(target, attributes.merge(remote: true)) do
text.to_s.html_safe
end
end
end
WillPaginate::ViewHelpers::LinkRenderer.class_eval do
def symbolized_update(target, other, blacklist = nil)
other.each_pair do |key, value|
key = key.to_sym
existing = target[key]
next if blacklist && blacklist.include?(key)
if value.respond_to?(:each_pair) and (existing.is_a?(Hash) or existing.nil?)
symbolized_update(existing || (target[key] = {}), value)
else
if value.instance_variable_defined?(:@parameters)
value = value.instance_variable_get(:@parameters)
end
target[key] = value
end
end
end
end
내 생각에 나는 유언장 링크의 렌더러를 동일하게 유지했습니다.
= will_paginate results, renderer: MaterializePagination::Rails
도우미를 다시 만드는 @Pierre의 훌륭한 답변에 이어 보기 업데이트와 관련된 몇 가지 후속 질문을 보았습니다(처음에는 문제가 있었습니다).@Pierre는 사용자가 js 응답을 생성해야 한다고 언급함으로써 이 문제를 해결합니다.도우미를 만든 후 수행한 작업은 다음과 같습니다.
내 쇼에서. about.erb.
<div id="see-comments">
<%= render @comments %>
</div>
<div id="pagination-comments">
<%= js_will_paginate @comments %>
</div>
저는 show.js.erb라는 다른 파일을 만들었습니다(그래서 쇼를 위한 두 가지 형식).
// to update comments
$("#see-comments").html("<%= j render @comments %>");
// to update the pagination links
$("#pagination-comments").html('<%= js_will_paginate @comments %>');
언급URL : https://stackoverflow.com/questions/13623953/how-to-implement-ajax-pagination-with-will-paginate-gem
'programing' 카테고리의 다른 글
볼륨에 단일 파일을 마운트하는 방법 (0) | 2023.08.02 |
---|---|
install wordpress with cliin docker에서 mariadb 컨테이너와의 "데이터베이스 연결 설정 오류"가 발생합니다. (0) | 2023.08.02 |
콜백 함수를 실행할 때 Angular2 구성 요소의 "this"가 정의되지 않았습니다. (0) | 2023.07.28 |
선택적 공백 정규식 (0) | 2023.07.28 |
MySQL에서 수백만 개의 행 업데이트 (0) | 2023.07.28 |