【问题标题】:Rails: radio button selection for nested forms objectsRails:嵌套表单对象的单选按钮选择
【发布时间】:2010-11-25 01:37:57
【问题描述】:

我有以下 photo_album 表单,它使用 Rails 的嵌套表单功能在更新 photo_album 时保存照片。并且在选择单选按钮值时遇到问题。我希望只有一张照片能够选择作为专辑封面,但是由于 rails 生成表单元素 ID 和名称的方式,我可以选择所有照片作为专辑封面。有什么解决方法吗?

<% form_for @photo_album do |f| %>
  <%= f.error_messages %>

  <% @photo_album.photos.each do |photo| %>
    <% f.fields_for :photos, photo do |photo_fields| %>
      <p>
       <%= image_tag url_for_image_column(photo, "data", :thumb) %>
      </p>
      <p>
       <%= photo_fields.label :title %> 
       <%= photo_fields.text_field :title %>
      </p>
      <p>
       <%= photo_fields.label :body %>  
       <%= photo_fields.text_area :body %>
      </p>
      <p>
       <%= photo_fields.radio_button :cover, "1" %>
       <%= photo_fields.label :cover, 'Album Cover', :class => 'option' %>  
       <%= photo_fields.check_box :_delete %>
       <%= photo_fields.label :_delete, 'Delete', :class => 'option' %> 
      </p>  
     <% end %>
   <% end %>

   <p>
     <%= f.submit @photo_album.new_record? ? 'Create' : 'Update' %>
    </p>
<% end %>  

以下是 rails 为单选按钮生成的 html(这是问题的一部分):

<p>
 <input type="radio" value="1" name="photo_album[photos_attributes][0][cover]" id="photo_album_photos_attributes_0_cover_1"/>
 <label for="photo_album_photos_attributes_0_cover" class="option">Album Cover</label>  
 <input type="hidden" value="0" name="photo_album[photos_attributes][0][_delete]"/><input type="checkbox" value="1" name="photo_album[photos_attributes][0][_delete]" id="photo_album_photos_attributes_0__delete"/>
 <label for="photo_album_photos_attributes_0__delete" class="option">Delete</label> 
</p>

【问题讨论】:

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


    【解决方案1】:

    我猜在这种情况下,您可能希望使用 radio_button_tag 并使用相同的名称。

    这应该很接近 - 你仍然需要弄清楚你什么时候想要传入 true:

    <%= radio_button_tag "cover", photo.id, todo %>
    

    您也可以使用 radio_button 帮助器指定名称,但它不太适合模型,所以 radio_button_tag 对我来说更有意义 - 我可能弄错了。

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 1970-01-01
      • 2011-07-30
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      相关资源
      最近更新 更多