Wednesday 23 September 2009

Holy crap that was a mind-f**k

nested forms - you have to love 'em.
Nesting with has_many was not too much of a problem. Follow the railscast and it all seems to work just fine - yes it was fiddly, but in the end it comes good.
Nesting with has_one - a total mind fuck.
With has_many you can use association.build to build all the objects you want and then use yr bog-standard controller to handle it for you with the update.
But has_one has a real gotcha. If you try and create two objects - which you may have to to get round the nil problem when using the form_for thingy, then if you try and use association_build, it updates both of them - immediately orphaning one of them as you can only have one associated object. And then all manner of horribleness starts.
After a long, long, long time screwing around with this - came up with the following:
def client_attributes=(client_attributes)
#this little beaut Returns the associated object. nil is returned if none is found (ie on new).
cl = client(force_reload = false)
if cl == nil
build_client(client_attributes)
else
client_attributes.each do |key, value|
unless key == 'id'
cl["#{key}"] = client_attributes["#{key}"]
end
end
client=(cl)
end
end

It is the normal virtual attribute you use to pick it up from the form, and then whack a method in the model. But you have to handle two different situations - one when it is a new build, in which case you won't have an existing client object - so you can go ahead and build it, and the other time when you do.
Then I have manually gone through the new attributes - and leaving aside the id, taken the new values by hand into a temp object (cl), given it the new values from the hash you pass over, and then save it to the child object (client).
Then when that gets handed over to the controller for the normal update, everything is in the right place and there is peace and brotherly love the world over.

Friday 18 September 2009

redgreen and autoSPEC

Ahhh - the command is autospec, not autotest (RTFM).
Had a problem getting redgreen to work - but commenting out the
require redgreen/autotest inside of ~/.autotest seems to have done the trick

Thursday 17 September 2009

Rspec

Have put off the day long enough. Got a simple new class to build (address class). Going to build it using rspec from the ground up - not use scaffold etc.
Wish me luck.