A blog application has posts and comments.
Each time a post is to be edited, a check needs to be made to
determine if the current user is the owner of the entry or not. Same
rule applies for deletion.
Similarly, each time a comment is to be deleted, a check needs to be
made to determine if the current user is an admin or not.
In other languages and frameworks( ie. catalyst or a custom made perl
framework) , a method is defined in the model class of the object and
in the controller, we load the object and call the method we defined
earlier to perform the check.
In this case, it would be (pseudocode like)
my $post = Posts->new();
if ( $post->check_access() )
output error message, "Insufficient permission to perform desired
My question is, how do we create methods in models and how to call
them from the controllers?
Any reference (url) would be much appreciated.
When showing user related then use the rails scoping, i.e. if you are
showing something to a user or only related to a user then always
scope it. Assuming you already have a user object called
current_user and you want to show comments or posts for that user then
Similarly when you are giving access to a single post or comment for a
user then in your controller
instead of simply doing
For checking edit and deletes or anything important, I would define a
method in my post / comment class like so
class Post < ActiveRecord::Base
return true if user_id == current_user.id
and before updating or deleting, I can use this method to determine
whether the current user is the owner using a before filter in my
controllers. For e.g.
Lets say you have methods called update and destroy in your
PostController where you would like to enforce this condition
class PostController < ApplicationController
before_filter :check_access, :only => [:update, :destroy]
# if you are doing this then you need before filter
@post = Post.find(params[:id])
# if you are always doing this then you don't need before filter
or operation_allowed? method in your model
@post = Post.find_by_id_and_user_id(params[:id], current_user.id)
# but in this case you need to show the flash message and redirect
the user when @post.nil?
flash[:error] = "You are not allowed to edit / delete this
Hope that makes sense.