will_paginate 帖子分页后删除群组中的帖子

will_paginate deletes posts in a group when posts are paginated

我正在使用 will_paginate 对群组中的帖子进行分页。 一个群组可能有很多帖子,我不想一次显示所有帖子。 出于某种奇怪的原因,我注意到当我执行 @group.posts = paginated_posts 时,很多帖子都从数据库中删除了,如 * groups_controller*.

中所示

我没有在@group 上保存,为什么帖子被删除了?

先测试

 69     it "Pagination – get one group and its posts" do
 70       10.times { Fabricate(:post, group: @group, user: @user) }
 71       puts "POST COUNT BEFORE #{@group.posts.count}"
 72       # byebug
 73       get group_path(@group, posts_per_page: 3)
 74       puts "POST COUNT AFTER #{@group.posts.count}"
 75       expect(response).to have_http_status(200)
 76       expect(@group).to be_present
 77     end

测试输出

Groups
  GET /group/:group_id?posts_per_page=10&posts_page=2
POST COUNT BEFORE 12
POST COUNT AFTER 3

groups_controller.rb

  9   def show
 10     paginated_posts = @group.posts.paginate(
 11       page: params[:posts_page],
 12       per_page: params[:posts_per_page] || 100000,
 13     )
 14     @group.posts = paginated_posts
 15     render json: @group
 16   end

日志

  (0.3ms)  RELEASE SAVEPOINT active_record_1
Started GET "/groups/33?posts_per_page=3" for 127.0.0.1 at 2018-09-18 12:52:13 +0000
Processing by GroupsController#show as HTML
  Parameters: {"posts_per_page"=>"3", "id"=>"33"}
  User Load (2.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" =  LIMIT   [["id", "78913bd2-4c72-4c73-ba75-421e154c830b"], ["LIMIT", 1]]
  Group Load (1.4ms)  SELECT  "groups".* FROM "groups" WHERE "groups"."id" =  LIMIT   [["id", 33], ["LIMIT", 1]]
  Post Load (2.2ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."group_id" =  LIMIT  OFFSET   [["group_id", 33], ["LIMIT", 3], ["OFFSET", 0]]
  Post Load (0.3ms)  SELECT "posts".* FROM "posts" WHERE "posts"."group_id" =   [["group_id", 33]]
   (0.4ms)  SAVEPOINT active_record_1
  Comment Load (0.5ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" =   [["post_id", 156]]
  PostImage Load (0.3ms)  SELECT "post_images".* FROM "post_images" WHERE "post_images"."post_id" =   [["post_id", 156]]
  Post Destroy (0.3ms)  DELETE FROM "posts" WHERE "posts"."id" =   [["id", 156]]
  Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" =   [["post_id", 157]]
  PostImage Load (0.3ms)  SELECT "post_images".* FROM "post_images" WHERE "post_images"."post_id" =   [["post_id", 157]]
  Post Destroy (0.3ms)  DELETE FROM "posts" WHERE "posts"."id" =   [["id", 157]]
  Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" =   [["post_id", 158]]

@group.posts = ... 并不像您想象的那样工作。如果你有一个一对多的关系,并且你将一个关联记录的数组分配给现有的 group 对象,记录集 和删除 group.id 外键立即。无需保存。

所以当你

@group.posts = paginated_posts

分页帖子分配给关联并且关联中的所有其他记录都从关联中删除。即刻。它们不一定被删除,但它们不再属于 @post

您可能想要更改您的 #to_json ... 或者添加

attr_accessor :page_of_posts

然后在你的控制器中

@group.page_of_posts = paginated_posts

并确保 page_of_posts 是 json 中呈现的内容。其他人可能会提出更好的方法。