以下是标准的posts#create
操作(app/controllers/posts_controller.rb
)。
在控制器级别,我想阻止匿名用户(未登录的用户)保存帖子。作为次要目标,如果用户未登录,我什至不想执行Post.new
行。我想知道实现此目的的最佳实践是什么。
另外,作为旁注,我不确定如何编写响应的json
部分。如果我在HTML
上下文中使用警报消息进行重定向,那么在JSON
世界中做出响应的好事是什么?
def create
@posting = Post.new(posting_params)
respond_to do |format|
if @posting.save
format.html { redirect_to @posting, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: @posting }
else
format.html { render action: 'new' }
format.json { render json: @posting.errors, status: :unprocessable_entity }
end
end
end
目前,我的代码中有以下行,位于Post.new
行上方:
redirect_to home_path, warning: 'You must be logged in to post.' and return unless user_signed_in?
我想另一个选项是如下所示,放置在if @posting.save
行上方。但实际上,我正在想看看其他人会怎么做。
unless user_signed_in?
format.html { redirect_to home_path, alert: 'You must be logged in to post.' and return }
format.json { render json: .....not sure what to put here..... }
end
非常感谢您的建议。
before_filter
适用于此类事情:
before_filter :confirm_user_signed_in, only: [:new, :create]
def confirm_user_signed_in
unless user_signed_in?
respond_to do |format|
format.html { redirect_to home_path, alert: 'You must be logged in to post.' and return }
format.json { render json: .....not sure what to put here..... }
end
end
end
至于在 JSON 场景中要呈现的内容,您根本无法渲染任何内容,但状态为 403(禁止访问)。您可以选择包含一些数据来解释 403 发生的原因,但对于如何显示这些数据没有标准。一些框架(我认为是 Backbone)会寻找包含 errors
键的哈希,可以将其设置为原因。
像这样:
format.json { render json: { errors: ["Login required."] }, status: 403 }
更好的做法是在过滤之前使用并提及如下操作列表:
before_filter :require_login, :only => [:new, :create]
尝试使用康康舞宝石。您不仅可以防止不需要的用户发布,还可以执行各种其他权限,这些权限不会使控制器膨胀。这些权限由您在名为 ability.rb 的单独文件中定义。
康康轨道广播
康康 Github