将可查看内容限制为创建它的用户

时间:2014-07-14 07:47:48

标签: ruby-on-rails-4 devise

感谢您抽出宝贵时间。我正在制作一个仅向创建该帖子的用户显示帖子的网络应用。我使用Rails 4和Devise Gem进行身份验证。我认为可能有使用范围的方法,但已经碰壁了。

这是我在github上的项目的链接:

https://github.com/sunkencity999/scratchitoff

1 个答案:

答案 0 :(得分:1)

在你的控制器中(让我们假设它的PostController)你可以这样写:

class PostsController << ApplicationController
    before_filter :restrict_user, :only => [:show, :view, :edit, :delete, :update]

    def show

    end

   def view
   end

   def edit
   end

   def delete
   end

   def update
   end

   private
   def restrict_user
       begin
           @post = current_user.posts.find(params[:id].to_i)
       rescue
           redirect_to "/", :error => "You don't have access to that post"
       end
   end
end

您可以使用@post

访问视图中的帖子

before_filter操作在控制器操作之前执行。 restrict_user操作检查current_user范围中是否存在具有给定ID的POST。 如果是这样,它会将该帖子分配给@post实例变量,如果不是,则会重定向到根路由(/),并显示错误消息。

您可以使用不同的方法,另一种解决方案可能是:

def restrict_user
    @post = current_user.posts.where(:id => params[:id].to_i)
    if @post.nil?
        # no access. your code logic here.
    else
        # user has access to that post do further code logic here.
    end
end

您也可以使用像Pundit这样的宝石来使用授权。

编辑:刚检查了你的github回购,看起来你已经在使用Pundit了。 然后,您应该将/app/policies/post_policy.rb中的PostPolicy编辑为以下内容:

class PostPolicy < ApplicationPolicy

  def index?
    user.present? and post.user_id == current_user.id
  end
end

没有时间测试这个。如果您遇到问题,我可以在我的机器上进行测试。 另请注意,此更改不会影响其他方法(如查看,编辑,删除,更新)。那么您应该调整我对索引所做的更改吗?对这些方法的行动也是如此。

相关问题