Posts [ 5 ]

Topic: Preventing access to all ActiveRecord::Base methods

Is there a quick way to do this, so that you can control access to the database through your model. Lets say you have a class that you want only a create and destroy method on... how do you keep the controller from access all the other methods ActiveRecord defines (but still use them in your own create/destroy methods?

Re: Preventing access to all ActiveRecord::Base methods

I thought the point of having private & protected methods was so you could only expose those methods that you want users of the class to have access to. And limit access to the class to only what is necessary. But ActiveRecord::Base opens up full access to the object through exposing the database.

Just as an example, let's say you create a plugin that has two simple methods:read and write... on some object in the database. Now some user can come in and call create, save, or delete, or destroy and mess with your objects in a way that you had not intended.

I guess I thought there was an easy way (like attr_reader/attr_writer to expose or protect + make private those active record methods).

Re: Preventing access to all ActiveRecord::Base methods

Although I haven't looked into it much, I doubt this would be easy to do because ActiveRecord goes through many different methods for destroying/editing/creating models. For example, you can call 'destroy' on a specific instance of a model to destroy it. Or you can call 'destroy' on the model's class and pass an id of the model you want to destroy. Or you can call destroy_all. There's also "delete" variations. Don't forget the :dependent option in the association definition.

Looking at the source, it appears many of these use the instance level 'destroy' method or the 'delete_all' method, but I don't know if it's the same for all cases. Probably the simplest thing to do is override before_destroy callback and raise an exception. You can do the same for the delete_all method since that bypasses the callback.

In short though, I think it is best to leave this in the hands of the developer and just provide good documentation on what should not be done. Nothing's going to stop them from executing a query directly on the database for example.