[LRUG] Setting default roles in a user record

James Adam james.adam at gmail.com
Tue Aug 7 03:35:06 PDT 2007


On 8/7/07, John Winters <john at sinodun.org.uk> wrote:
> James Adam wrote:
> > Oops - you probably want to have that user saved and returned from the
> > method, but you get the idea :)
> >
> > On 8/7/07, James Adam <james.adam at gmail.com> wrote:
> >> Or, sidestep the whole "initialization" issue:
> >>
> >>   class User < ActiveRecord::Base
> >>     def self.create_with_default_roles(*attributes)
> >>       new_user = new(*attributes)
> >>       Roles.find_all_default_roles.each do |role| # or whatever
> >>         new_user.roles << role
> >>       end
> >>     end
> >>     # etc...
> >>   end
> >>
> >> My point is, you don't need this to happen *automagically*. Just
> >> define a new method that does what you want, and call it wherever you
> >> want this default user created.
>
> This sounds a promising approach.  Could I just override the default
> "new" method with my own which sets default values if no parameters are
> passed in?

This isn't quite what I meant; the point is that you don't need to
override anything. Rather than redefining the behaviour of "new" or
"create", you define an entirely different method which performs the
operations that you need, returning a new user in your
custom-initialized state.

Letting ActiveRecord's "new" method behave as it wants to should avoid
any problems if they ever change its behaviour.

HTH,

-- 
* J *
  ~



More information about the Chat mailing list