你的问题在这里:
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