1

我正在使用nested_form gem,它允许用户动态添加和删除表单字段。它工作正常,但我希望能够阻止用户删除第一个 file_field,并且仅在用户添加的字段时才显示“删除”链接。我的“_form”和“_photo_fields”部分如下。我认为解决方案是执行类似“如果此字段不是页面上其类型的第一个字段,则显示‘删除’链接”之类的操作,但我不知道如何实现。感谢您提供的任何见解。

_form.html.erb:

<%= simple_nested_form_for @service_offering do |f|%>

... Other Fields ...

<%= f.fields_for :photos do |builder| %>
    <%= render 'photo_fields', :f => builder %>
<%end%>

<%= f.button :submit %>

<p><%= f.link_to_add "Add Photo", :photos %></p>    

_photo_fields.html.erb:

<% if f.object.new_record? %>

<%= f.label :photo %>  
<%= f.file_field :photo %>
# This is where I want to drop that if statement, but I am not sure what it should be.
<%= f.link_to_remove "Remove" %>
#
<%end%>

<% unless f.object.new_record? %>

<%= link_to( image_tag(f.object.photo.url(:thumb))) %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove" %>

<%end%>
4

2 回答 2

2

您无法将其从 ERB 中隐藏起来,因为在 fields_for 块内呈现的内容随后被用作“添加新”按钮的模板。因此,如果您在此处隐藏删除链接,则任何添加的项目都不会具有删除链接。

当我查看 nested_form_for 代码时,它没有对此的本机支持。最简单但不理想的解决方案是通过 CSS 或 JS 在客户端隐藏删除链接。

我用这个 JS 解决了它:

$(function() {
  $('a[data-nested-form-disable-first]').each(function() {
    var nested_container = $(this).closest('.fields');

    // check if is first
    if (!nested_container.prev().is('.fields')) {
        $(this).remove();
    }
  });
});

然后添加 'data-nested-form-disable-first' 以删除链接定义:

<%= f.link_to_remove 'Remove', 'data-nested-form-disable-first' => '' %>

它仅在您确保不可移除字段在加载时位于页面中时才有效。

于 2013-05-22T09:23:41.970 回答
0

我在这里看到两个选项:

  1. 如果可以询问您的照片是否可以删除,那将是最简单的解决方案
  2. 您可以尝试通过 CSS 隐藏表单中的链接。

照片 API

尝试通过以下方法扩展您的照片模型

class Photo ...
  def removable?
    ...
  end
end

_photo_fields.html.erb:

...
<%= f.file_field :photo %>
<% if f.object.photo.removable? %>
  <%= f.link_to_remove "Remove" %>
<% end %>

使用 CSS

我不确定,但应该可以通过:

  1. div为您的照片字段添加一个
  2. 将相关规则添加到您的 CSS 中。

所以这里是代码(只有你应该更改或添加的片段:

_photo_fields.html.erb:

<div class="photo_fields">
   ...
   <%= f.link_to_remove "Remove", :class => "remove" %>
   ...
</div>

应用程序.css:

div.photo_field:first-child > a.remove {
  display: none;
}

如果可能的话,第一个解决方案是正确的,因为它根本不允许移除不可移除的东西。第二个是隐藏链接的解决方法,但要弱得多。

于 2011-12-10T19:17:44.410 回答