Ruby on rails 4 将可查看内容限制为创建它的用户
谢谢你抽出时间。我正在寻找一个web应用程序,只向创建该帖子的用户显示帖子。我正在使用Rails 4和Desive Gem进行身份验证。我在想也许有一种方法可以使用scope,但我遇到了麻烦 以下是我在github上的项目链接: 在控制器中(假设其后控制器),您可以编写如下内容:Ruby on rails 4 将可查看内容限制为创建它的用户,ruby-on-rails-4,devise,Ruby On Rails 4,Devise,谢谢你抽出时间。我正在寻找一个web应用程序,只向创建该帖子的用户显示帖子。我正在使用Rails 4和Desive Gem进行身份验证。我在想也许有一种方法可以使用scope,但我遇到了麻烦 以下是我在github上的项目链接: 在控制器中(假设其后控制器),您可以编写如下内容: class PostsController << ApplicationController before_filter :restrict_user, :only => [:show, :v
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
class PostPolicy < ApplicationPolicy
def index?
user.present? and post.user_id == current_user.id
end
end
您还可以使用诸如Pundit之类的gem来使用授权
编辑:刚刚检查了你的github回购,看起来你已经在使用Pundit了。
然后,您应该将/app/policies/post_policy.rb中的PostPolicy
编辑为如下内容:
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
class PostPolicy < ApplicationPolicy
def index?
user.present? and post.user_id == current_user.id
end
end
类后策略
还没有时间来测试这个。如果你有问题,我可以在我的机器上测试。
还要注意,此更改不会影响其他方法(如查看、编辑、删除、更新)。所以你应该调整我对索引所做的更改?对这些方法也采取行动。如果我能再请求一点帮助吗?使用你的方法我得到了这个错误:未定义的局部变量或方法'post',你从哪里得到这个错误?在视图中还是在控制器中?你能提交你的更改吗?