2013-11-01 35 views
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 

您的建议非常感谢。

+0

您是否使用了认证库像设计?简而言之,使用'before_filter'确保登录并且仅适用于某些操作,比如'before_filter:ensure_logged_in,只:[:new,:create,:destroy]' –

回答

1

一个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发生的原因,但没有关于数据如何显示的标准。一些框架(骨干,我认为)将寻找包含errors键的散列,可以将其设置为原因。

喜欢的东西:

format.json { render json: { errors: ["Login required."] }, status: 403 } 
1

更好的做法是以前像这样的行动过滤器和提列表中使用:

before_filter :require_login, :only => [:new, :create] 
1

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

cancan Railscast

cancan Github

相关问题