인증을 위해 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과 같은 추가 보석을 사용하고 싶지 않습니다.
음, 내가 컨트롤러 내부의 논리에 대해 생각했다 ...하지만 그래,이 꽤 괜찮습니다. 고맙습니다. –