首页 > 解决方案 > Rails 随机选择 3 个不同的帖子

问题描述

大家好,所以我正在写一个小博客,并且有一个新的部分想要添加。“编辑选择”部分,所以基本上我想添加一个小 div,其中包含 3 个从博客中随机挑选的帖子。问题是我不知道如何从所有帖子中只显示三个随机选择的标题。我尝试了@posts.sample(3),它显示了帖子的全部记录。我只想显示标题。我想在帖子索引视图架构上显示编辑选择

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "user_id"
    t.string "nickname"
  end

Posts_controller

class PostsController < ApplicationController
  before_action :current, only: [:show, :edit, :update, :destroy]
  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(posts_params)
    @post.user = current_user
    if @post.save
      redirect_to posts_path
    else
      render :new
    end
  end

  def edit
  end

  def update
    @post.user = current_user
    @post.update(posts_params)
    @post.save
    redirect_to posts_path
  end

  def destroy
    if @post.destroy
      redirect_to posts_path
    end
  end

  private

  def posts_params
    params.require(:post).permit(:title, :content, :user_id, :image, :nickname)
  end

  def current
    @post = Post.find_by(id: params[:id])
  end

end

post_index.html.erb

<%= render "layouts/blog_header" %>
<% @posts.each do |post| %>
  <div class="posts">
    <div>
      <% unless !post.image.attached? %>
        <%= image_tag post.image, class: "post-index-image" %><br>
      <% end %>
    </div>
    <p class="post-index-title"><%= link_to post.title, post_path(post.id), class: "post-index-title" %></p>
    <p>Published by: <strong><%= post.user.nickname %></strong></p>
  </div>
<% end %>
<%= @posts.sample(3) %>

谢谢!

标签: ruby-on-railsrubyrandom

解决方案


当你使用 PostgreSQL 时,我会从这样的事情开始:

@posts.order('RANDOM()').limit(3)

或者当你在 MySQL 上时:

@posts.order('RAND()').limit(3)

推荐阅读