【问题标题】:Ruby On Rails Pagination and delete :through associationRuby On Rails 分页和删除:通过关联
【发布时间】:2013-07-05 18:39:39
【问题描述】:

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

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**

如果我打电话给

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

关联表CollectionItemsAssoc中的记录被删除

我真的不明白

感谢您的帮助

【问题讨论】:

  • 发布两个请求的服务器日志

标签: ruby-on-rails pagination


【解决方案1】:

问题在于获取项目的代码

@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

此外,您还可以覆盖 Collection 模型中的 to_json 方法。

【讨论】:

  • 太棒了!效果很好。我刚刚开始在 Rails 上使用 ruby​​,但挣扎的部分是最有趣的
猜你喜欢
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多