I've had a couple of instances where I've wanted to work with an attribute in
an ActiveRecord through another class. For example I'm storing time zones in
my database as strings, but I want to always deal with them through a
TimeZone object. Same goes for time intervals.

I've been using aggregations to do with with some success, but if someone can
suggest a more appropriate way, please let me know.

If aggregations are the right way to go, I've got some issues.

First, if you've got aggregations all setup to work to convert from the
database, they still don't seem to get handled when converting from a web
form (via update_attributes). I then stumbled on to multiparameter
attributes, which seems to know about aggregations. That was working for a
tag where I generate the name myself "employee[time_zone(1)]", but causes an
error if you try to use text_field('employee', 'time_zone(1)'). 

I think that the FormHelper should handle multiparameter attribute syntax, if
people agree, I'll do a patch for it.

Then I thought about it, and I think you shouldn't have to use the
multiparameter syntax in the case where you have an aggregation with just one
parameter. It should just do the cast automatically. So, I came up with the
patch at the end of this mail.

It seems to work ok for me, but I thought I'd see what other people have to
say before doing any more work on it.


--- activerecord-1.13.2/lib/active_record/base.rb.orig  Fri Jan 13 15:58:45 2006
+++ activerecord-1.13.2/lib/active_record/base.rb       Wed Jan 25 18:50:27 2006
@@ -1334,7 +1334,17 @@
 
         multi_parameter_attributes = []
         remove_attributes_protected_from_mass_assignment(attributes).each do 
|k, v|
-          k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + 
"=", v)
+          if k.include?("(")
+            multi_parameter_attributes << [ k, v ]
+            next
+          end
+         reflection = self.class.reflect_on_aggregation(k.to_sym)
+          if reflection
+           klass = reflection.klass
+           send(k + "=", Time == klass ? klass.local(v) : klass.new(v))
+            next
+         end
+         send(k + "=", v)
         end
         assign_multiparameter_attributes(multi_parameter_attributes)
       end


_______________________________________________
Rails-core mailing list
Rails-core@lists.rubyonrails.org
http://lists.rubyonrails.org/mailman/listinfo/rails-core

Reply via email to