2017-04-10 1 views
2

私は2つのテーブルを持っています:投稿とユーザー(関係は多対多です)、ユーザーはFavoritePostテーブルを持っています(user_idとpost_idで構成されています) ルート:
GET 'favorite_posts'、へ: 'favorite_postsの#インデックス' (ユーザー/:user_idを/ favorite_posts) 私ability.rbで:私のコントローラ(favorite_posts_controller.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 

class FavoritePostsController < ApplicationController 
    load_and_authorize_resource through: :current_user 

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

だから、私はability.rbを通して他のユーザーの好きな投稿を持つページへのリダイレクトをブロックする必要があります。私は何をする必要がありますか?

答えて

0

カンカンメンテナからこのquoteを見てみましょう:

ユーザーがまたは 何かが、何 特定の非常にコンテキストがあるからアプリが行う操作を行うことができないことができるかどうかの質問に答えることができ

カンカン私はability.rbファイルには適していないと思います。あなたは他のユーザーが現在のユーザーのお気に入りの投稿を表示させたくない場合は、それはあなたのfavorite_posts_controllerbefore_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 
関連する問題