我已经在这里通过一些有用的答案帮助我的应用程序完成最后的润色,并想知道如何执行此功能。我在post_controller
文件中设置了一个想法,我希望根据创建日期显示最近创建的前10个帖子。我也打算为我的评论这样做。我在views/post/index.html.erb
文件中显示所有用户的帖子。我在posts_controller: posts = Post.order('created_at DESC').limit(10)
中编写了这行代码。我在这里进行了彻底的搜索,但是不明白其他一些用户是如何使用它的,有什么见解?提前谢谢。
posts_controller
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :vote]
before_action :require_user, only: [:new, :create, :edit, :update, :vote]
before_action :require_creator, only:[:edit, :update]
def index
posts = Post.order('created_at DESC').limit(10)
@posts = Post.all.page(params[:page]).per_page(10)
end
def show
@comment = Comment.new
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.creator = current_user
if @post.save
flash[:notice] = "You created a post!"
redirect_to posts_path
else
render :new
end
end
def edit
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
flash[:notice] = "You updated the post!"
redirect_to post_path(@post)
else
render :edit
end
end
def vote
Vote.create(voteable: @post, creator: current_user, vote: params[:vote])
respond_to do |format|
format.js { render :vote } # Renders views/posts/vote.js.erb
end
end
private
def post_params
params.require(:post).permit(:url, :title, :description)
end
def set_post
@post = Post.find(params[:id])
end
def require_creator
access_denied if @post.creator != current_user
end
end
答案 0 :(得分:0)
您在posts
操作中声明的index
变量将无法在您的视图中显示。您需要做的是使用实例变量更新您要检索帖子的行,如下所示:
def index
@posts = Post.page(params[:page]).order('created_at DESC').per_page(10)
end