views:

125

answers:

1

Hi, Can someone explain the following code sample what does "album[photo_attributes][]" mean I found this code here http://infrastacks.com/?p=57

<div class="photo">
<% fields_for "album[photo_attributes][]", photo do |p| %>
  <p>
    <%= p.label :Photo %><br />
    <%= p.file_field :data, :index => nil %>
    <%= link_to_function "delete", "remove_field($(this), ('.photo'))" %>
  </p>
<% end %>
</div>
+1  A: 

Literally, it's a structure that tells rails to group all the submissions together in a single hash table so you can walk through them one at a time.

So in this case, the hashtable 'album[][]' is double indexed. By not putting an explicit index number for the second item in the hash (indicated by the open and closed brackets after [photo_attributes]), rails knows to join all the submissions with that hash name (albums) and first index value (photo attributes) together into a single hash table where the object associated photo_attributes is an array. Each entry in this array is a hash with a value at the index :data.

## From the code on that page
params[:album][:photo_attributes]
#This turns out to be an array of hashes. Each hash has one key/value pair in it. The key is "data" and the value is the file information. Example:
{"data"=>#<File:/var/folders/56/56dUsTxtHaKheeiHSoaE1++++TI/-Tmp-/CGI20081216-17582-14p6wd2-0>}

params[:album][:photo_attributes].each { |p| p[:data] } # this is a loop that would get you the data for each photo submitted.
aronchick
Thank you very much :)
Felix