2013-07-05 34 views
0

我遇到了一個奇怪的現象,考慮以下型號:Ruby on Rails的分頁和刪除:通過關聯

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 

    respond_to do |format| 
     format.json { render json: @collection.to_json(:include => {:items => @collection}) } 
    end 
    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** 

然後如果我叫的關聯表CollectionItemsAssoc被刪除

/retailapp/collections/1?format=json&**page=2** 

記錄我真的不明白這一點

感謝你的幫助

+0

發佈兩個請求的服務器日誌 – bluehallu

回答

0

問題是代碼fe TCH的項目

@ collection.items = Collection.find(PARAMS [:ID])。項

它分配所獲取的項集電對象。

你需要改變的響應,以支持聯想的分頁對象

  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 

此外,您可以覆蓋to_json收集模型內部的方法。

+0

太棒了!效果很好。我剛剛開始在軌道上的紅寶石,但掙扎的部分是最有趣的 – user2553252