2012-03-09 3 views
1

인증을 위해 devise를 사용하고 있으므로 모든 컨트롤러에 current_user가 있습니다. 내 모델은 다음과 같습니다 점검 객체가 컨트롤러의 current_user에 속합니다 (has_and_belongs_to_many)

class User < ActiveRecord::Base 
    has_many_and_belongs_to :posts 
end 

class Posts < ActiveRecord::Base 
    has_many_and_belongs_to :users 
end 

class PostsController < ApplicationController 
    before_filter :authenticate_user! 

    def show 
     @post = Post.find(params:id) 
     # need to check if @post belongs to current_user here 
     # ... 
    end 

    def edit 
     @post = Post.find(params:id) 
     # need to check if @post belongs to current_user here 
     # ... 
    end 
end 

조치의 일부

가 PostsController 에 (예를 들어 편집보기) 포스트는 DB에서 가져온 경우 CURRENT_USER에 속하는 확인해야합니다. 그렇지 않은 경우 404 오류를 표시하고 실행을 종료하려고합니다 (찾기 호출 직후).

분명히 DRY 상태를 유지하고 싶기 때문에 모든 작업에 동일한 코드를 작성하고 싶지는 않습니다.

PostsController에 개인 메서드를 작성하려고 시도했지만 개인 메서드에서 404로 리디렉션 할 수없고 즉시 실행을 중단 할 수 없습니다. 나는 각 작업 전에 실행할 것이기 때문에

before_filter이 작동하지 않습니다, 나는 각 작업 내부에 반입되고있는 @post 객체가 필요합니다.

마지막으로 나는 CanCan과 같은 추가 보석을 사용하고 싶지 않습니다.

답변

2

나는이 테스트를하지 않은,하지만이 같은 것을 할 수 있어야한다 : 컨트롤러에서 다음

class Post < ActiveRecord::Base 
    has_many_and_belongs_to :posts 

    scope :for_user, lambda { |user| joins(:users).where("user_id = ?", user.id) 
end 

: 논리가 반복되지

Post.for_user(user).find(params[:id]) 

그 방법을하고 재사용의 .

+0

음, 내가 컨트롤러 내부의 논리에 대해 생각했다 ...하지만 그래,이 꽤 괜찮습니다. 고맙습니다. –

0

부울을 반환하고 반환 값을 기반으로 기본 메서드에서 리디렉션하는 개인 메서드를 작성하는 방법은 어떻습니까?

class PostsController < ApplicationController 
    before_filter :authenticate_user! 

    def show 
     redirect_to 404 if !check_my_stuff? 
     # need to check if @post belongs to current_user here 
     # ... 
    end 

    def edit 
     redirect_to 404 if !check_my_stuff? 
     # need to check if @post belongs to current_user here 
     # ... 
    end 

    private 

    def check_my_stuff? 
     @post = Post.find_by_id(params:id) 
     (@post.user == current_user) ? true : false 
    end 
end 
+1

예, 시도했지만 모든 작업에서 리디렉션이 반복됩니다. –

0

컨트롤러 코드

class PostsController < ApplicationController 
    before_filter :authenticate_user! 
    before filter :load_post, :only => [:edit, :update, :show] 

    private 
    def load_post 
    @post = current_user.posts.find_by_id(params[:id) 
    @post ||= invalid_url! # defined in app controller 
    end 
end 
관련 문제