开发者

Rails Fields For Code Sample [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. 开发者_运维问答 Closed 9 years ago.

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>


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜