以下是標準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]' –