2011-01-15 36 views
16

Tôi tự hỏi nếu có ai có thể vui lòng cho tôi biết nếu will_paginate có thể hỗ trợ JSON ra khỏi hộp hoặc nếu điều này đã bị tấn công?will_paginate hỗ trợ JSON?

Tôi muốn thêm dữ liệu trang vào phản hồi JSON trong khi will_paginate quản lý phân trang.

Trả lời

38

Something trong dòng:

@posts = Post.paginate :page => params[:page] 

respond_to do |format| 
    format.json { 
    render :json => { 
     :current_page => @posts.current_page, 
     :per_page => @posts.per_page, 
     :total_entries => @posts.total_entries, 
     :entries => @posts 
    } 
    } 
end 

Khi bạn tìm ra những gì định dạng mà bạn muốn, bạn luôn có thể xác định một phương pháp to_json trên WillPaginate :: Bộ sưu tập.

+0

có đó là những gì tôi muốn làm, bây giờ tôi biết cách hoạt động của nó có thể trả về những gì tôi cần bằng cách hiển thị thẳng đến JSON, tuy nhiên, thay đổi định dạng như thế này rất hữu ích. –

+3

xem tài liệu API GitHub [1] để biết cách mã hóa trang tốt hơn trong phản hồi của bạn (gợi ý: đặt mã vào tiêu đề) [1]: http://developer.github.com/v3/#pagination – asymmetric

+2

Cách bạn đã tìm thấy những phương pháp này? Chúng không được liệt kê trong wiki will_paginate. – Francisco

1

will_paginate chỉ lấy lại các bản ghi theo cách được cắt lát. Vì vậy, nó chỉ nhận được một mảng từ cơ sở dữ liệu của bạn.

Khi bạn kết xuất dưới dạng json, đó là đường ray đi qua mảng đối tượng và gọi as_json trên chúng.

Vì vậy, có, bạn có thể will_paginate hiển thị dưới dạng json.

+0

Nhưng tôi đoán tôi sẽ phải hack nó để nó bao gồm tổng số trang trong phản hồi JSON cùng với dữ liệu phân trang. –

+1

đó là tất cả trong phản hồi từ Model.paginate - vì vậy bạn sẽ chỉ cần tìm nó trong phản ứng json. –

+0

Tôi cũng sẽ xem xét điều đó. @mislav cung cấp và ví dụ về những gì tôi đang tìm kiếm, tuy nhiên, tôi có thể thấy rằng chỉ cần hiển thị đầu ra tiêu chuẩn như JSON cũng nên chứa thông tin mà tôi cần. –

1

tôi khuyên bạn nên xem railscast này: Pagination with AJAX

+1

Tôi không sử dụng RJS vì vậy dữ liệu phải nằm trong phản hồi JSON –

8

Thêm Pagination để một API

Tôi tìm thấy một giải pháp dễ dàng để API Json đáp ứng Pagination với will_pagination.

bắt đầu bằng cách tạo ra một phương pháp học trong ApplicationController rằng sẽ tạo ra một after_filter rằng sẽ thiết lập các pagination meta-data trong các tiêu đề phản ứng:

application_controller.rb

class ApplicationController < ActionController::Base 

    protected 
    def self.set_pagination_headers(name, options = {}) 
    after_filter(options) do |controller| 
     results = instance_variable_get("@#{name}") 
     headers["X-Pagination"] = { 
     total: results.total_entries, 
     total_pages: results.total_pages, 
     first_page: results.current_page == 1, 
     last_page: results.next_page.blank?, 
     previous_page: results.previous_page, 
     next_page: results.next_page, 
     out_of_bounds: results.out_of_bounds?, 
     offset: results.offset 
     }.to_json 
    end 
    end 

end 

Sau đó, trong bộ điều khiển chúng tôi muốn thêm tiêu đề phân trang, chúng tôi có thể gọi nó như sau:

widgets_controller.rb

class Api::V1::WidgetsController < Api::V1::BaseController 
    set_pagination_headers :widgets, only: [:index] 

    def index 
    @widgets = Widget.all.paginate(params).order("created_at desc") 
    respond_with @widgets 
    end 

end 

tiêu đề phản ứng trông giống như

> Cache-Control:max-age=0, private, must-revalidate 
> Connection:keep-alive Content-Type:application/json; charset=utf-8 
> Etag:"fe70f7bae4c6e5cdea7867aa7fc0c7b4" 
> X-Pagination:{"total":14,"total_pages":1,"first_page":true,"last_page":true,"previous_page":null,"next_page":null,"out_of_bounds":false,"offset":0} 
> Server:thin 1.3.1 codename Triple Espresso 
> Set-Cookie:_widgets_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTAzYjVlNzkwZTIyNzU4YTYwMDU0M2MwOTQ2ZWI3YWU2BjsAVEkiDWxhc3RfdXJsBjsARkkiM2h0dHA6Ly9tYWluYW5kbWUtc3RhZ2luZy5oZXJva3VhcHAuY29tL3VzZXJzLzEGOwBGSSIQX2NzcmZfdG9rZW4GOwBGSSIxdjd0SEp6cVhKamh5YTh1cnBUdmpBb0w5aVA0bS9QTEdON3g1UlFUYnBkND0GOwBG--71b3a24c216a414d8db04f312b5300c818e6bba4; 
> path=/; HttpOnly Transfer-Encoding:Identity 
> X-Request-Id:61b383ade49cba8b24a715a453ed6e1f X-Runtime:0.191485 
> X-Ua-Compatible:IE=Edge,chrome=1 

Source -Adding Pagination to an API

+0

Đây là phân trang tuyệt vời cho một API. Không sửa đổi dữ liệu được trả về, đặt thông tin phân trang trong tiêu đề. Giải pháp siêu sạch, chơi tốt với những người khác như Angular, những người muốn một mảng kết quả trở lại cho một chỉ mục/danh sách/truy vấn. – Ryan

2

Các giải pháp dễ dàng nhất này

def index 
    @posts = Post.all.paginate(:page => params[:page], :per_page => 4) 
    render :json => @posts.to_json(:methods => [:image_url]) 
    end 

bạn chỉ cần thêm gem, will_pagination

nó làm việc cho tôi

0

Cái này giúp tôi:

https://github.com/rails-api/active_model_serializers/blob/master/docs/howto/add_pagination_links.md

Phỏng theo:

Thêm phương pháp này để điều khiển cơ sở API của bạn.

def pagination_dict(collection) 
    { 
    current_page: collection.current_page, 
    next_page: collection.next_page, 
    prev_page: collection.prev_page, # use collection.previous_page when using will_paginate 
    total_pages: collection.total_pages, 
    total_count: collection.total_count # use collection.total_entries when using will_paginate 
    } 
end 

Sau đó, sử dụng nó trên phương thức hiển thị của bạn.

render json: posts, meta: pagination_dict(posts)