On 25.01.2009, at 14:27, Charlotte wrote:

> I wanted to set some default values for a model. It took me a while
> but I finally got it to work but I was wondering if there's a better
> way to do the following (please see the "after :save" part):


As far as I understand, you want your users to have at least one  
context with default name of "uncategorized",
and at least one calendar.

1. add :default => "uncategorized" to Context model's name property
2. add validates_is_unique :name, :scope => [:user] (or whatever  
association name is) to Context model
3. add

before :save do
   self.contexts.create  if self.contexts.empty?
   self.calendar.create if self.calendar.blank?
end

or something similar, to User model.

Optionally you can move two lines in before :save hook into methods  
with meaningful names:

before :save do
   ensure_default_context_is_present
   ensure_calendar_is_present
end

def ensure_default_context_is_present
   self.contexts.create  if self.contexts.empty?
end

def ensure_calendar_is_present
   self.calendar.create if self.calendar.blank?
end

but in this particular case it hardly makes things any easier to read.

MK


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"DataMapper" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/datamapper?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to