hey everyone so I'm working on a small blog and there is a new section a want to add. An "editor's choice" section so basically i want to add a small div that contains 3 randomly pick posts from the blog. The problem is I do not know how to show only three randomely select titles from all the posts. I tried @posts.sample(3) and that shows the entire record of the Post. I just want to show the title only. I want to show the editors choice on the posts index view Schema
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) %>
Thanks!
Aucun commentaire:
Enregistrer un commentaire