Rails模板:包含显示的索引的其余部分



我有一个相当典型的博客应用程序,其中包括show(post)和index (posts)方法:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  def show
    @post = Post.find(params[:id])
  end
  def index
    # redirect_to post_path(Post.last) and return
    @posts = Post.all.order(created_at: :desc).where('text like ?', "%#{params[:search]}%").page(params[:page]).per_page(6)
  end

我该如何在每个帖子(分页)下面包括所有其他帖子——减去你正在看的那个。所以我得到了这样的东西:

POST 4: blah blah blah

---- archives -----

POST 5: blah blah blah

POST 3: blah blah blah

POST 2: blah blah blah

POST 1: blah blah blah

类似于

def show
  @post = Post.find(params[:id])
  @other_posts = Post.where.not(id: @post)
end

我使用这个而不是其他解决方案的原因是因为您对@other_posts的查询可能不包含@post

Ruby的一个很酷的特性是能够减去数组。你可以试试这个:

def show
  @post = Post.find(params[:id])
  @other_posts = Post.all - Array(@post)
end

然后在视图中为@other_posts变量分页

最新更新