Tuesday, August 12, 2008

getting Rails forms to be obedient.

The default Rails assumption is that you are doing things with ActiveRecord objects directly basically all the time.  This is not a horrible assumption, but most of my Rails projects at LocaModa have not been "in charge", and so I've had to twist the expectations a little bit.  

Most recently, I needed a form that was basically just a wrapper around a function that did direct inserts/deletes.  Additionally, the form needed default values filled in.  I'm a bad, bad man, and probably opened up a new level of hell for myself.  But here's how I did it.

<% form_for :qux, :url => {:controller => das_controller, :action => das_action} do |f| %> 

<%= f.text_field :foo, :value => @value %>

<%= f.submit "Suck it" %>

<% end %> 

The Rails form_for docs are surprisingly opaque on this sort of thing, which I think is probably a mistake.  Documenting possibilities, even the bad ones, is a very good thing, especially if the bad ones are accompanied with an explanation of why they should be avoided.  

No comments: