简体   繁体   English

在Ruby on Rails 4.2中使用Cocoon gem的嵌套表单

[英]Nested forms using the Cocoon gem in Ruby on Rails 4.2

I'm building a web app using Rails 4.2 and I have a model called Strategy which has a has_many relationship to a Tactic model. 我正在使用Rails 4.2构建Web应用程序,并且有一个名为Strategy的模型,该模型与Tactic模型具有has_many关系。

To create a view for Strategy, I need to have many nested Tactics on the form. 要为策略创建视图,我需要在表单上有许多嵌套的战术。 I've been using the Cocoon gem to develop this view. 我一直在使用Cocoon gem开发这种视图。

So far, I've been able to get the form to work properly for the most part but the issue is that I wanted to add a Type attribute to my Tactic model. 到目前为止,我已经能够使表单在大多数情况下正常工作,但问题是我想在Tactic模型中添加Type属性。

For a given strategy, I want to have 3 tactics of one given type, and 2 models of another. 对于给定的策略,我想拥有一种给定类型的3种策略,以及另一种给定2种模型。

The issue is that rendering my view, all five models are listed sequentially without any room for putting in my own HTML code around them. 问题在于渲染我的视图时,所有五个模型都按顺序列出,而没有空间放置我自己的HTML代码。

Is there a simple way to separate out which of these are rendered? 是否有一种简单的方法可以区分出其中的哪些内容? Right now, my view looks as follows... 现在,我的看法如下...

<%= form_for @strategy do |f| %>
    <div class="strategy">
        <%= f.label :name %>
        <%= f.text_field :name %>
    </div>

    <div class="tactics">
        <%= f.fields_for :tactics do |i| %>
            <%= render 'tactics_fields', f: i %>
        <% end %>
    </div>

    <div class="buttons">
        <%= f.button "Save Strategy", class: 'button' %>
    </div>
<% end %>

If anyone can offer any advice, it would be greatly appreciated. 如果有人可以提供任何建议,将不胜感激。

Are you wanting the form to be rendered so that each Strategy has exactly 5 Tactics listed below it, of which 3 are of one type and 2 are of another? 您是否希望呈现该表单,以便每个策略正好在其下面列出了5种策略,其中3种是一种类型,而2种是另一种类型?

If so, you can do this in your controller: 如果是这样,您可以在控制器中执行以下操作:

5.times do
  tactic = @strategy.tactics.build
  tactic.tactic_type = 'tactic_type'
end

Also, note that using an attribute called type is not a good idea. 另外,请注意,使用名为type的属性不是一个好主意。 Use something like tactic_type instead. 使用类似tactic_type东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM