ruby-on-rails - 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) %>
谢谢!
解决方案
当你使用 PostgreSQL 时,我会从这样的事情开始:
@posts.order('RANDOM()').limit(3)
或者当你在 MySQL 上时:
@posts.order('RAND()').limit(3)
推荐阅读
- ios - 如何使标签的背景图像适合标签的框架大小
- python - Pandas Dataframe str.split错误传递的项目数错误
- c# - c# 在构建时替换文件中的标记
- reactjs - reactjs为什么在setState中使用传播运算符
- oracle18c - xepdb1 中的 Oracle 18c XE expdp 特定模式
- c++ - 连续 x 没有。A,然后在 (nx) 个 B 之后
- sapui5 - 获取特定语言环境的 i18n 文本
- python - 如何使用列表理解语法从 2 个列表中返回 2 个列表?
- php - Ajax 表不显示任何内容
- c - 将给定的尾数、指数和符号转换为浮点数?