I’m using devise for authentification, so I have a current_user in every controller. My models are:
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
Some of the actions in PostsController (for instance show and edit) need to check if the Post fetched from the DB belongs to the current_user. If it doesn’t, I want to show a 404 error and end the execution (just after the find call).
Obviously I would like to stay DRY, so I don’t want to write the same code in every action.
I’ve tried to write a private method in PostsController, however from a private method I cannot redirect to a 404 and then interrupt the execution immediately.
A before_filter won’t work since I would be executed before each action, and I need the @post object which is being fetched inside each action.
Finally I don’t want to use additional gems like CanCan.
I have not tested this, but you should be able to do something like this:
Then in your controller:
That way the logic is not repeated and it’s reusable.