1

用户编辑视图:

<%= form_for(@user, :html => {:multipart => true}) do |f| %>
    <%= f.text_field :name, placeholder: :name %>
    <%= f.submit "Save" %>

    <%= f.fields_for :photos do |photo_fields| %>
        <%= image_tag(photo_fields.object.photo.url(:user_thumbnail) %>
        <%= f.radio_button :avatar, @selected_photo_number %>

因此,我会显示用户上传的所有照片,并在每张照片旁边显示一个单选按钮。我怎样才能做到这一点,以便当我单击第一个 @selected = 0 和第二个 @selected = 1 等等。基本上我需要知道照片在数组@user.photos[] 中的哪个位置。谢谢!

而不是@selected_photo_number我需要像photo_fields.object.place数组一样的东西?

4

1 回答 1

4

我想你正在寻找index.

>> array = [1,2,3,4,5]
>> array.index(1) # 0
>> array.index(3) # 2

each_with_index但是使用您的代码,我认为您正在寻找

<% f.object.photos.each_with_index do |photo, index| %>
  <%= f.fields_for :photos, [photo] do |photo_fields| %>
    <%= image_tag(photo_fields.object.photo.url(:user_thumbnail) %>
    <%= f.radio_button :avatar, index %>
于 2013-04-18T08:46:26.980 回答