Model based method - how to create it?

hi, all,

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() )
{
    perform update/deletion
}
else
{
    output error message, "Insufficient permission to perform desired
action"
}

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.

Thank you :slight_smile:

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
use

current_user.comments

current_user.posts

Similarly when you are giving access to a single post or comment for a
user then in your controller

Post.find_by_id_and_user_id(id, current_user.id)

instead of simply doing

Post.find id

For checking edit and deletes or anything important, I would define a
method in my post / comment class like so
class Post < ActiveRecord::Base
  def operation_allowed?(current_user)
     return true if user_id == current_user.id
     false
  end
end

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]

  def update
     # 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?

    #do update
  end

  def destroy
    #do delete
  end

  private

  def check_access
     unless @post.operation_allowed?(current_user)
        flash[:error] = "You are not allowed to edit / delete this
post"
     end
  end

end

Hope that makes sense.

nas