[LRUG] Setting default roles in a user record

Pratik Naik pratik at thinkwares.com
Tue Aug 7 07:29:01 PDT 2007


How about

===
class Whatever

def with_roles=(roles)
  self.roles << roles
end

end

Whatever.new :with_roles => Roles.find_default_roles
===

On 8/7/07, Daniel Lucraft <dan at fluentradical.com> wrote:
>
> --- 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
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>



More information about the Chat mailing list