views:

48

answers:

1

I have a fields_for tag, where I specify the prefix (lets say for some good reasons), and this is supposed to represent a one-to-one relationship.

I am trying to represent a relationship

widget has_many thingamagigs
thingamagig has_one whatchamacallit

The field_for code is:

fields_for "widgt[thingamagigs_attributes][][whatchamacallit_attributes]", thingamagig.whatchamacallit do |x|

which generates names (wrongly):

widget[thingamagigs_attributes][][whatchamacallit_attributes][][value]

The better solution would be

t.fields_for :whatchamacallit do |x|

where t = fields_for the thingamagig... However if I do that, the following names are generated

widgt[thingamagigs_attributes][whatchamacallit_attributes][]

which is completely wrong as all other fields for a thingamagig is...

widgt[thingamagigs_attributes][][name]

So in all cases I am screwed. The original field_for using a string cannot be used with accepts_nested_attributes_for :whatchamacallit since whatchamacallit is a singular relationship and an object is expected not an array. The second fields_for will simply not work because rails cannot parse the params object correctly. Is there a way to tell the first forms_for to not add the [] after [whatchamacallit_attributes] in all field names?

My current solution is to augment the model with

def whatchamacallit_attributes=(whatchamacallit_attributes)
  assign_nested_attributes_for_one_to_one_association(:whatchamacallit, whatchamacallit_attributes[0])
end

Which will work even with the broken form fields. However this feels extremely hacky, does anyone have a solution?

A: 
def whatchamacallit_attributes=(whatchamacallit_attributes)
  assign_nested_attributes_for_one_to_one_association(:whatchamacallit, whatchamacallit_attributes[0])
end

Looks like I have to stick with this solution since nothing else was offered.

Dmitriy Likhten