【问题标题】:rails: Paginate posts for current forum_thread_idrails:为当前 forum_thread_id 的帖子分页
【发布时间】:2016-02-18 07:19:02
【问题描述】:

我正在尝试在它的 forum_thread_id 下对我的帖子进行分页。 当我对@forum_posts 进行分页时,我得到的是所有帖子,而不是特定于我所在线程 ID 的帖子。

我正在使用 will_paginate 进行分页。

这可能是我没有看到的任何简单的解决方法。

【问题讨论】:

标签: ruby-on-rails ruby pagination


【解决方案1】:

这就是我的工作方式。

@forum_posts = @forum_thread.forum_posts.paginate(:page => params[:page], :per_page => 2)

【讨论】:

    【解决方案2】:

    你的问题在这里:

    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
    

    顺便说一句(这是高级的),您最好将您的 threadpost 模型放入 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
    

    【讨论】:

      【解决方案3】:

      您必须使用 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-10
        • 2018-05-03
        相关资源
        最近更新 更多