gpt4 book ai didi

ruby-on-rails - 阻止重定向到其他帖子页面

转载 作者:太空宇宙 更新时间:2023-11-03 16:42:21 25 4
gpt4 key购买 nike

我有 2 个表:posts 和 users(他们的关系是多对多的),User 有很多 favorite_posts(和 FavoritePost 表(它由 user_id 和 post_id 组成)。所以,我有一条路线:
获取'favorite_posts',到:'favorite_posts#index'(用户/:user_id/favorite_posts)在我的能力范围内.rb:

class Ability 
include CanCan::Ability

def initialize(user)
user ||= User.new
if user.new_record?
can :read, [Post]
else
can :read, [Post]
can :manage, [Post], owner_id: user.id
can :manage, [FavoritePost], user_id: user.id
end
end
end

在我的 Controller 中(favorite_posts_controller.rb):

class FavoritePostsController < ApplicationController
load_and_authorize_resource through: :current_user

def index
@favorite_posts = User.find(params[:user_id]).favorite_posts
end

因此,我需要通过 ability.rb 阻止重定向到包含其他用户最喜欢帖子的页面。我需要做什么?

最佳答案

看看这个quote来自 CanCan 维护者:

CanCan can answer the question whether the user can or can't do something, but what the app does from there is very context specific and I don't think is a good fit for the ability.rb file.

如果您不想让其他用户查看当前用户最喜欢的帖子,最好将其放在您的favorite_posts_controller 中的before_action 过滤器中:

 class FavoritePostsController < ApplicationController
load_and_authorize_resource through: :current_user
before_action :correct_user, only: [:index] # add any other actions you want

def index
@favorite_posts = current_user.favorite_posts.all
end

private

def correct_user
user = User.find(params[:user_id])
redirect_to root_url unless current_user && current_user == user
end
end

关于ruby-on-rails - 阻止重定向到其他帖子页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43321173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com