如何解决允许其他注册用户访问帖子
我正在使用Devise进行身份验证,并希望注册用户能够与其他注册用户共享其帖子。目前,我的应用程序设置仅允许创建的用户查看,编辑和删除他们的帖子。
发布控制器
class PostsController < ApplicationController
before_action :set_post,only: [:show,:edit,:update,:destroy]
before_action :authenticate_user!
before_action :require_active_user,:destroy]
def index
@post = Post.where("user_id = ?",current_user.id)
end
def private
def require_active_user
if current_user != @post.user
redirect_to root_path,alert: "Access Denied!"
end
end
end
end
模型
class Post < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable,:lockable,:timeoutable,:trackable and :omniauthable
devise :database_authenticatable,:registerable,:recoverable,:rememberable,:validatable
has_many :posts
end
架构
create_table "Posts",force: :cascade do |t|
t.integer "user_id"
t.string "title"
t.text "description"
t.datetime "created_at",precision: 6,null: false
t.datetime "updated_at",null: false
end
我设想创建的用户在输入字段中输入电子邮件地址,如果该电子邮件是活动用户,那么该用户现在将能够查看该帖子。
解决方法
- 如果您要模拟(以其他用户身份登录),这就是我在应用程序上为管理员所做的
moodle/course:managegroups
做什么是以用户身份登录管理员(我不建议一般用户登录,但这对管理员有帮助)
如果您想赋予用户创建,查看,编辑和删除的能力,可以使用pundit
Pundit提供了一组帮助您指导定期利用的助手 Ruby类和面向对象的设计模式可以构建简单, 强大且可扩展的授权系统。
在您的gem文件中包含gem #app/controllers/admins/users_controller.rb
class Admins::UsersController < AdminController
def login_as
sign_in(User.find(params[:user_id]),:bypass => true)
redirect_to users_root_path
end
end
在您的应用程序控制器中包含Pundit
gem "pundit"
您的第一个政策如下
class ApplicationController < ActionController::Base
include Pundit
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。