以下是标准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:ensure_logged_in,只:[:new,:create,:destroy]' –