Ruby on rails RubyonRails分页和删除:通过关联

Ruby on rails RubyonRails分页和删除:通过关联,ruby-on-rails,pagination,Ruby On Rails,Pagination,考虑到以下模型,我遇到了一个奇怪的情况: class Collection < ActiveRecord::Base attr_accessible :name, :season, :year has_many :collection_items_assocs has_many :items, :through => :collection_items_assocs end class Item < ActiveRecord::Base attr_a

考虑到以下模型,我遇到了一个奇怪的情况:

class Collection < ActiveRecord::Base
  attr_accessible :name, :season, :year
    has_many :collection_items_assocs
    has_many :items, :through => :collection_items_assocs

end

class Item < ActiveRecord::Base
  attr_accessible :name, :reference, :item_type_id
  has_many :pictures
  has_one :item_type

end


class CollectionItemsAssoc < ActiveRecord::Base
   attr_accessible :collection_id, :item_id
   belongs_to :item
   belongs_to :collection
end
但是当我尝试包含这样的分页(项目)时

# GET /collections/1
  # GET /collections/1.json
  def show
    @collection = Collection.find(params[:id])

   **@collection.items = Collection.find(params[:id]).items.paginate(:page => params[:page],:per_page =>1)**

    respond_to do |format|
      format.json { render json: @collection.to_json(:include => {:items => @collection}) }
    end
  end
它适用于以下调用

/retailapp/collections/1?format=json&**page=1**
如果我打电话

/retailapp/collections/1?format=json&**page=2**
关联表
CollectionItemsAssoc
中的记录将被删除

我真的不明白


感谢您的帮助

问题在于获取项目的代码

@collection.items=collection.find(params[:id]).items

它将获取的项目分配给当前集合对象

您需要更改响应以支持关联对象的分页

  def show
   @collection = Collection.find(params[:id])
    respond_to do |format|
          format.json {
            json_hash = @collection.as_json
            json_hash[:items] = @collection.items.paginate(:page => params[:page],:per_page =>1).as_json
            render json:  json_hash.to_json
            }
  end

此外,您还可以在集合模型内覆盖到_json方法。

发布两个requestsAwesome的服务器日志!效果很好。我刚刚开始使用RubyonRails,但挣扎的部分是最有趣的
  def show
   @collection = Collection.find(params[:id])
    respond_to do |format|
          format.json {
            json_hash = @collection.as_json
            json_hash[:items] = @collection.items.paginate(:page => params[:page],:per_page =>1).as_json
            render json:  json_hash.to_json
            }
  end