[LRUG] Setting default roles in a user record

Daniel Lucraft dan at fluentradical.com
Tue Aug 7 07:24:19 PDT 2007


--- John Winters <john at sinodun.org.uk> wrote:
> 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.

Then how about this?

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

best,
Dan



More information about the Chat mailing list