【问题标题】:Rails: paginate association with to_json/to_xmlRails:与 to_json/to_xml 的分页关联
【发布时间】:2012-11-30 11:08:54
【问题描述】:

我有一个名为 Playlists 的模型,它有_and_belongs_to_many :songs

在我的 PlaylistController 中,我调用了 respond_with(@playlist, :include => :songs) 这样我就可以返回 json 和 xml 输出。

但是,某些播放列表包含数百首歌曲。所以我想让调用者在调用中发送 ?limit=X&offset=Y (默认值分别为 25 和 0)。但是我如何在序列化过程中将此限制和偏移量传递给关联?我试过了

@playlist.songs = @playlist.songs.limit(l).offset(o)

但这带来了一些不幸的结果。 :(

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails xml json activerecord pagination


    【解决方案1】:

    这似乎是分页库的任务。我们正在使用 will_paginate。我们的调用如下所示:

    collection.paginate page => 2, :per_page => 10
    

    【讨论】:

    • 很抱歉,据我所知,这不会改变 to_xml 或 as_json 方法使用的 @playlist.songs 集合,这些方法由 render_with 调用。或者,也许我错过了什么?您如何建议我在我的 @playlist 对象上使用它来对与之关联的 songs 集合进行分页?
    【解决方案2】:

    这是我所做的:

    我添加了使用集合对模型进行分页并检索分页集合的方法:

    # models/playlist.rb
    def paginate_songs(limit, offset)
        @paginated_songs = Array.new
        songs.limit(limit).offset(offset).each do |song|
            @paginated_songs << song
        end
    end
    
    def paginated_songs
        return @paginated_songs
    end   
    

    我向控制器添加了一些逻辑,它将对对象进行分页并在响应中包含分页集合:

    # controllers/playlists_controller.rb
    @playlist.paginate_songs(l, o)
    respond_with(@playlist, :methods => [ :paginated_songs ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多