【问题标题】:How do you find what place in an array something is?你如何找到数组中某物的位置?
【发布时间】:2013-04-11 07:04:56
【问题描述】:

用户编辑视图:

<%= 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[] 中的哪个位置。谢谢!

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

【问题讨论】:

    标签: ruby-on-rails arrays forms radio-button


    【解决方案1】:

    我想你正在寻找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 %>
    

    【讨论】:

    • 答案是:
    • 我一直在尝试做 photo_fields.object.index 不知道语法
    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2017-02-05
    • 2022-06-19
    • 2019-11-30
    • 2013-02-21
    • 2014-05-11
    相关资源
    最近更新 更多