And, back to the Rails 3 app today.
Adding custom attributes to to_json
When dealing with forms that are submitted remotely, sometimes you need to provide information that you wouldn’t otherwise think that hard about. In this case, we are creating Jobs for Customers. When you create a Job, it’s always for a Customer. We display the customer_name as an autocomplete field in the form, and have a hidden customer_id field that is updated when you make an autocomplete selection. Simple.
But what about after the form submit? You get back a Job to display in your page, and you want that Customer Name field. Tough noogies, you only get Job attributes back from to_json. Or… do you?
This link pointed me in the correct direction:
The meat of the stuff I needed was here:
Fixing a bug in the rails3-jquery-autocomplete
Creating default values for a Rails model
Lots of bad answers for this one. But the proper answer (for my particular case) is “after_initialize”. See the comment by insane_dreamer on the supposedly “correct” answer to this question:
This turned into a real bear. Anyone care to comment on why
validates_associated :customer, :on => [:create, :save, :update]
doesn’t work, but
does? The validation never seemed to fail (on bad data) with the first one. Aren’t they the same thing?