5

我有使用嵌套表单的茧,如果您单击添加字段链接,它会插入输入字段。如何自动呈现第一个输入,然后在单击“添加字段”时插入其他输入?

4

2 回答 2

7

在您的控制器中,使用此代码。在下面的代码中,jobs 是一个模型,并且配置文件接受_nested_attributes_for 作业。将 @profile 替换为您的表单的用途。第二行是构建表单域的内容,除非表单域已经存在。

def new
    @profile = current_user.profile
    1.times {@profile.jobs.build} unless current_user.profile.jobs.any?
end

自单数以来,您可能需要不时更改。实际上,您也许可以完全摆脱 times 方法并执行以下操作:

def new
    @profile = current_user.profile
    @profile.jobs.build unless current_user.profile.jobs.any?
end
于 2013-11-10T23:10:54.523 回答
1

The quick and dirty solution is to just use jQuery (which Cocoon requires anyways) to click Cocoon's "add item" button when the page loads:

$(document).ready(function() { $(".add_fields").click() } );

I use this in my "new" views, but not in "edit" views, since there may already be some nested items and I don't want to make assumptions. But you could also use script to count the nested item forms and conditionally show the "new item" fields.

于 2014-11-13T07:58:05.690 回答