0

以下是标准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

非常感谢您的建议。

4

3 回答 3

1

更好的做法是在过滤器之前使用并提及如下操作列表:

before_filter :require_login, :only => [:new, :create]
于 2013-11-01T05:14:28.237 回答
1

Abefore_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 }
于 2013-11-01T05:14:57.377 回答
1

尝试使用康康宝石。您不仅可以阻止不需要的用户发帖,还可以执行其他各种权限,这些权限不会使控制器膨胀。这些权限由您在名为ability.rb 的单独文件中定义。

康康Railscast

康康Github

于 2013-11-01T05:20:31.667 回答