flatten in inputs_for_nested_attributes should have a level #786

eLod opened this Issue Jan 30, 2012 · 3 comments


None yet

2 participants

eLod commented Jan 30, 2012

inputs_for_nested_attributes does a fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten (i'm using 1.x but 2.x is the same), which will swallow an empty array. so if i do inputs :for => [:association, []] (meaning i want to have an empty list not the current association list, but still have the 'bindings' for inputs and labels) the flatten will simply swallow the empty array. the solution would be to use flatten(1). my goal is to create a has_many list (input) that the user can only use to add new items (e.g. the associated objects would be further processed upon submit, so though i need to have/process the associated objects i don't want to show/list them to the user afterwards), not sure if i overlooked something.


So this is effectively what the current code does:

ruby-1.8.7-p249 :005 > [[:association, []],{}].flatten
 => []

Which would be applied something like this:

fields_for(:association, {})

And you'd like to see this instead:

ruby-1.8.7-p249 :006 > [[:association, []],{}].flatten(1)
 => [:association, [], {}]

Applied like this:

fields_for(:association, [], {})

I can't find anything in the Rails docs that explicitly says this works, but it seems like it should based on the examples provided. As long as someone is certain this works, that's cool with me!

The last final check is if the more common case still works as expected, and it does:

> [:association,{ :hi => :there}].flatten(1)
 => [:association, {:hi=>:there}]

Sounds good, have you got time for a pull request? Would love to get this in the 2.1 RC ASAP.

eLod commented Jan 31, 2012

well fields_for_nested_model (which is called from fields_for) will act as if the association would be an empty list (because if association argument is an empty array: convert_to_model does nothing and an empty array does not respond to :presisted? but responds to :to_ary) but it is not documented.

if you are okay with that i can create a pull request.

p.s. the first code fragment in your comment is wrong, the return value should be [:association, {}], though you are using that in the next fragment so i guess it's just a typo

p.s.2 flatten will only touch arrays (e.g, will call flatten only on its array children), so it wont touch the options hash


@eLod sure, create away!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment