以下是标准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
非常感谢您的建议。