Tik’s Blog

ร้อยแปดพันเก้า

Result Summary สำหรับ will_paginate ใน RailsSpace

with one comment

ต่อจากโพสต์ที่แล้ว ใน Listing 10.19 มีใช้ item_count, current_page, first_item, และก็ last_item ซึ่งเราไม่มีใน Rails 2.2

การเปลี่ยนโค้ดให้ทำงานกับ will_paginate ก็ไม่ยากนัก เพราะว่า array ที่คืนมาโดย will_paginate ก็มี method พิเศษต่างๆเช่นกันคือ total_pages, total_entries, current_page, และก็ offset เพื่อแทนค่าจำนวนหน้าทั้งหมด, จำนวน item ทั้งหมดในผลลัพธ์, เลขที่หน้าปัจจุบัน, และก็ index ของ item แรกของหน้า (อย่าลืมว่า index ของ array เริ่มต้นที่เลขศูนย์ เพราะฉะนั้นเราต้องบวก 1 ตอนแสดงผล)

โค้ดที่แทนก็กลายเป็น​:

  Found <%= pluralize(@specs.total_entries, "match") %>.
  <% if @specs.total_pages > 1 %>
    <% first_item = @specs.offset + 1 %>
    <% last_item = @specs.offset + @specs.length %>
    Displaying users <%= first_item %>–<%= last_item %>
  <% end %>

เท่านี้ก็เรียบร้อย (เนื่องจากว่า will_paginate ไม่มี first_item และ last_item เราจึงต้องคำนวนเอง)

อัพเดท: เพิ่งเปิดเจอลิงก์ของ RailsSpace เมื่อปีที่แล้วที่อธิบายการแปลงเป็น will_paginate  คล้ายๆกัันแต่เจ๋งกว่าตรงที่โค้ดของลิงก์นี้ย้าย first_item, last_item, และ paginated ไปไว้ใน WillPaginate class เลย เจ๋ง…ลืมไปว่ากำลังทำงานกับ Ruby อยู่ :p

Written by sukita

มีนาคม 12, 2009 ที่ 10:36 pm

บันทึกโพสใน Programming

Tagged with

มีการตอบกลับหนึ่งครั้ง

Subscribe to comments with RSS.

  1. [...] a comment » ในโพสก่อนหน้าเกี่ยวกับการแบ่งหน้าใน RailsSpace [...]


ใส่ความเห็น