[Rails] Modifying "Find" to always add a condition?

Mathias Stjernström mathias at globalinn.se
Thu Mar 2 20:15:51 GMT 2006


Hi Greg!
I have been working on a plugin for a couple of days that i think do  
what you want.
I call it Acts as restricted. Its one of those Acts_as plugins, DUH.
You simply add acts_as_restricted to your model and then tree columns  
to the model table
owner_id, group_id and restricted

owner_id is the owner of the object, group_id is the group the object  
belongs to and restricted is a integer that handles the current  
permissions for the object.

The permission can be:

OWNER_READ, OWNER_WRITE, OWNER_DELETE
GROUP_READ, GROUP_WRITE, GROUP_DELETE
WORLD_READ, WORLD_WRITE, WORLD_DELETE

The plugin then overrides the find/destroy/save/count methods of that  
object to check if the permissions is correct for the current user.

I have only been using rails for a couple of weeks so a cannot  
guarantee that it's fail-safe,
but it works pretty good so far ;-)

I am waiting for ruby-forge approval for my project and then i put it  
out in public.


Cheers!

Mathias Stjernstrom




On Mar 2, 2006, at 11:24 AM, Greg Edwards wrote:

> I'd like to always add a condition to any version of "find" (e.g.
> Thing.find(), Thing.find_by_name(), Thing.find_by_whatever) so that in
> addition to whatever conditions are set, an additional condition is  
> set
> :conditions=>"user_id=#{current_user.id}"
>
> I'd like to make sure that a user only sees/edits/creates entries  
> in the
> database that have the user_id field set to their id. I could wrap  
> all of my
> controller functions (create/new/show/edit/list) with
>     begin
> 	#note having to add to the ":conditions" field
> 	@thing = Thing.find(params[:id],
> :conditions=>"user_id=#{current_user.id}")
> 	rescue
>       	render :text=>"I'm sorry, you do not have access to that  
> record."
> 	end
> ...but clearly that is immensely un-DRY. AND, it removes the  
> ability to use
> the helpful Thing.find_by_name/etc functions.
>
> The goal is to make all versions of "find" work.
>
> Is it possible to change one function in the model and make it work?
>
> Thanks,
> -Greg
>
> Greg Edwards
> CTO, Eyetools Inc.
> (916) 792 4538
>
>
> _______________________________________________
> Rails mailing list
> Rails at lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails


--
Mathias Stjernström
mathias at globalinn.se

Direktnr:  08 - 525 09 112
Växel:     020 - 140 00 60
Fax:       020 - 140 00 61







More information about the Rails mailing list