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, i.e. 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
#do update
end
def destroy
#do delete
end
private
def check_access(post)
unless post.operation_allowed?(current_user)
flash[:error] = "You are not allowed to edit / delete this
post"
end
end
end
On Dec 11, 6:27 am, ct9a <[email protected]> wrote:
> 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 :)
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.