我试图在其下面的论坛_thread_id中对我的帖子进行分页。 当我对@forum_posts进行分页时,我收到了所有帖子,而不是我所在的线程ID特有的帖子。
我使用will_paginate进行分页。
这可能是我没见过的任何简单修复。
答案 0 :(得分:0)
你必须使用ForumThread id过滤查询,尝试这样的事情(相应地修改代码)
def show
@forum_post = ForumPost.new
@forum_posts = ForumPost.where(forum_thread_id: @forum_thread.id).paginate(:page => params[:page], :per_page => 3)
end
答案 1 :(得分:0)
你的问题在这里:
def show
@forum_post = ForumPost.new
@forum_posts = ForumThread.find(params[:id])
@forum_posts = ForumPost.paginate(:page => params[:page], :per_page => 3)
end
您正在对等同于ForumPost.all
进行分页,这意味着您将收回所有帖子,无论他们是哪个thread
的一部分。
你需要:
def show
@forum_post = ForumPost.new
@forum_thread = ForumThread.find params[:id]
@forum_posts = @forum_thread.paginate(page: params[:page], per_page: 3)
end
假设您有以下设置:
#app/models/forum_thread.rb
class ForumThread < ActiveRecord::Base
has_many :forum_posts
end
#app/models/forum_post.rb
class ForumPost < ActiveRecord::Base
belongs_to :forum_thread
end
顺便说一下(这是先进的),您将thread
和post
模型放入Forum
模块会更好:
#app/models/forum.rb
class Forum < ActiveRecord::Base
has_many :threads, class_name: "Forum::Thread"
end
#app/models/forum/thread.rb
class Forum::Thread < ActiveRecord::Base
belongs_to :forum
has_many :posts, class_name: "Forum::Post"
end
#app/models/forum/post.rb
class Forum::Post < ActiveRecord::Base
belongs_to :thread, class_name: "Forum::Thread"
end
这将允许您使用以下内容:
#config/routes.rb
scope path: ":forum_id", as: "forum" do
resources :threads do
resources :posts
end
end
#app/controllers/forum/threads_controller.rb
class Forum::ThreadsController < ApplicationController
def show
@forum = Forum.find params[:id]
@threads = @forum.threads
end
end
答案 2 :(得分:0)
这就是我的工作方式。
@forum_posts = @forum_thread.forum_posts.paginate(:page => params[:page], :per_page => 2)