嘿我正在使用rails创建一个博客,这是我的第一个应用。我正在尝试通过仪表板进行必须首先批准的评论。这是我目前的代码。
帖子控制器
class PostsController < ApplicationController
before_filter :authorize, only: [:edit, :update, :destroy, :create, :new]
def index
@posts = Post.where(:state => "published").order("created_at DESC")
end
def new
@post = Post.new
end
def show
@post = Post.find(params[:id])
redirect_to_good_slug(@post) and return if bad_slug?(@post)
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to dashboard_path
else
render 'new'
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :text, :author, :short, :photo, :state))
redirect_to dashboard_path
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to dashboard_path
end
private
def post_params
params.require(:post).permit(:title, :text, :author, :short, :photo, :state)
end
end
仪表板控制器
class DashboardController < ApplicationController
before_filter :authorize, only: [:index]
def index
@posts = Post.order("created_at DESC")
end
end
评论控制器
class CommentsController < ApplicationController
before_filter :authorize, only: [:destroy]
def create
@post = Post.find(params[:post_id])
@comment =
@post.comments.create(comments_params)
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def comments_params
params.require(:comment).permit(:commenter, :body)
end
end
评论模型
class Comment < ActiveRecord::Base
belongs_to :post
end
最后是路线
resources :dashboard
resources :posts do
resources :comments
end
再一次,我对后端dev和ruby很新,所以如果需要我可以提供更多信息。我想如果我能把所有评论都放到仪表板上,我就可以把剩余的评论搞清楚了。
谢谢!
答案 0 :(得分:0)
您需要创建一个Dashboard
控制器,具有访问权限的用户可以访问该控制器。对于index
操作,您可以执行类似的操作。
def index
@posts = Post.find(approved: false)
end
您还可以将范围添加到Post
模型
class Post < ActiveRecord::Base
scope :approved, -> {where(approved: false)}
end
然后你可以做
def index
@posts = Post.approved
end