我正在使用will_paginate对群组中的帖子进行分页。
一个论坛中可能有很多帖子,但我不想一次显示所有帖子。
出于某些奇怪的原因,我注意到{groupscontroller *中显示的@group.posts = paginated_posts
操作从数据库中删除了很多帖子。
我没有在@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" = $1 LIMIT $2 [["id", "78913bd2-4c72-4c73-ba75-421e154c830b"], ["LIMIT", 1]]
Group Load (1.4ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT $2 [["id", 33], ["LIMIT", 1]]
Post Load (2.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."group_id" = $1 LIMIT $2 OFFSET $3 [["group_id", 33], ["LIMIT", 3], ["OFFSET", 0]]
Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."group_id" = $1 [["group_id", 33]]
(0.4ms) SAVEPOINT active_record_1
Comment Load (0.5ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = $1 [["post_id", 156]]
PostImage Load (0.3ms) SELECT "post_images".* FROM "post_images" WHERE "post_images"."post_id" = $1 [["post_id", 156]]
Post Destroy (0.3ms) DELETE FROM "posts" WHERE "posts"."id" = $1 [["id", 156]]
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = $1 [["post_id", 157]]
PostImage Load (0.3ms) SELECT "post_images".* FROM "post_images" WHERE "post_images"."post_id" = $1 [["post_id", 157]]
Post Destroy (0.3ms) DELETE FROM "posts" WHERE "posts"."id" = $1 [["id", 157]]
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = $1 [["post_id", 158]]
答案 0 :(得分:0)
@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中呈现的内容。其他人可能会建议一种更好的方法。