[LRUG] Setting default roles in a user record

John Winters john at sinodun.org.uk
Tue Aug 7 01:02:44 PDT 2007


Hello there,

I'm working on a rails application and for user authorisation I'm using 
the User/Roles/Rights technique which I've seen suggested in quite a few 
places.  This works fine, but I'm struggling to add a little extra 
functionality.

I realised after a bit of use that almost every time I created a new 
user through the application I was ticking the same two Role boxes.  For 
speed of entry it therefore seemed logical to set these up as defaults 
for newly created users, and the correct place to put it seemed to me to 
be in the Model.  I'm struggling however to see exactly where to put it.

I thought I'd solved it by adding the relevant code to the 
after_initialize callback in the User model, like this:

   def after_initialize
     for role in Role.find(:all)
       if role.default_value
         self.roles << role
       end
     end
   end

but although that seemed to work correctly I realised after a while that 
the roles were being added every time a user record was accessed, not 
just when the user was first created.

Obviously I could put the logic in the controller instead, but that 
seems to me to be the wrong place.  Is there anywhere I can put the code 
  in the model which will cause it to be executed *only* for the 
creation of a brand new user?  (It also needs to happen before the new 
user dialogue is displayed so it can't be done in before_create.  If it 
were done there then the operator would not see that the new user had 
been given these roles, and wouldn't get the chance to remove them if 
they were inappropriate.)

The best solution I've thought of so far is to add a set_defaults method 
to the model and invoke that at the appropriate point in the controller, 
but is that the right way to do it?

TIA,
John



More information about the Chat mailing list