pcg79
pcg79

Reputation: 1283

Can I lock a table in Rails? (And should I?)

I have a small table in my Rails app that contains static data (user Roles). It shouldn't ever change. I'm wondering if it's possible to lock the table to keep anyone (namely developers) from accidentally changing it in production.

Or should I have not put that data into the database at all? Should it have been hardcoded somewhere to make editing more difficult and, at least, auditable (git blame)?

Upvotes: 1

Views: 692

Answers (3)

tmaximini
tmaximini

Reputation: 8503

I would probably make use of attr_accesible

if you write something like:

class Role < ActiveRecord::Base
  attr_accessible #none
end

you could at least prevent any assignment from the rails side, but it does not prevent any direct modifications through developers with database access.

see also this thread: How I can set 'attr_accessible' in order to NOT allow access to ANY of the fields FOR a model using Ruby on Rails?

Upvotes: 1

Joe Van Dyk
Joe Van Dyk

Reputation: 6940

You can use a trigger to prevent updates to the table (assuming you can't add a new db user).

Or, use a view and ensure all read requests go through it. (probably by removing the ActiveRecord class that corresponds to the table.

Upvotes: 0

Daniel Lyons
Daniel Lyons

Reputation: 22803

The right way to do this is with permissions. Change the ownership of the table to another user, and grant the production database user SELECT only.

I would say the right place for these kinds of things is probably the database. That way if they ever need to change, you can change them in the database, and you don't have to redeploy your application (assuming it will notice the change).

You didn't ask this, but your wording brought it to mind so I'll say it anyway: you should never need to explicitly LOCK a table with PostgreSQL. If you think this is something you need to do, you should make sure what you're worried about can actually happen under MVCC and that transactions aren't going to do the right thing for you.

Upvotes: 1

Related Questions