I'm doing a list of family members, each with aradiobutton for head
of household. After the household record and the records for each
person are created, it is easy to set the hoh field to the person
wanted. The problem comes if I try to set this field before the
create. Then the field is 0, and this isn't updated after the record
is created.
Show us how you are setting the field, presumably increatein the controller.
Colin
I was using a variable called hoh in the household (master) record.
This was holding the id number of the person (child) record selected.
This worked fine for existing records, but got lost with records
created at the time of the save, as these records had no id yet.
Someone else suggested that I put the hoh variable in the person
records, but if I do this, each radio button is separate, and there is
no way to allow only one selection.
It seems to me that there must be a way to do this with Active Record
Callbacks. After the record is created, it has an id. Couldn't I test
each person record after create, and if it has the radio button
selected, pass the id to the Household.hoh variable..
But for this... Is there a way to tell if the radio button is selected
if it points to a variable somewhere else ?? Or is there a way to get
Rails to just do this at the right time the way it does with parent/
child records, setting all id's and parent_id's ??
Too many question marks.
Use an :after_create callback in those cases; you will have the ID at that point and you can use it. Remember, you will need to set any relationship keys directly, not at the object level, since you can't call save again in an after_create (I don't think). Here's my after_save method from a similar setup:
def set_primary
self.update_attributes( :role_id => self.roles.first.id ) if self.roles.first
end
This is from inside a Title, which has_many roles, has_many people through roles, and belongs_to one role (designating the "primary" person, like the author or the editor -- the one that people think of when they're looking for that book, even though lots of people may have contributed to it).
I needed to go this route because I was using Ryan Bates' nested_form gem, and so I was adding roles to a title that hadn't been saved yet -- very similar to your setup if I recall correctly. Since I can't designate a primary in the #new method, because nothing has an ID yet, I use this callback to sort things out, and count on my editors to always choose the most important person first. I have a new_record? test in my view to hide the radio buttons in that case, and show them in the #edit view of the same form.
Walter