我试图在食谱书的编辑/创建部分创建嵌套字段,用于成分,方向和器具,但只显示字段的轮廓,没有任何嵌套位。
模型
class Recipe < ApplicationRecord
has_many :ingredients
has_many :directions
has_many :utensils
accepts_nested_attributes_for :ingredients, reject_if: proc { |attributes|
attributes['name'].blank? }, allow_destroy: true
accepts_nested_attributes_for :directions, reject_if: proc { |attributes|
attributes['step'].blank? }, allow_destroy: true
accepts_nested_attributes_for :utensils, reject_if: proc { |attributes|
attributes['name'].blank? }, allow_destroy: true
end
class Ingredient < ApplicationRecord
belongs_to :recipe
end
class Direction < ApplicationRecord
belongs_to :recipe
end
class Utensil < ApplicationRecord
belongs_to :recipe
end
食谱控制器(参数)
def recipe_params
params.require(:recipe).permit(:title, :description, :image,
ingredients_attributes: [:id, :name, :_destroy], directions_attributes:
[:id, :step, :_destroy], utensils_attributes: [:id, :name, :_destroy])
end
查看
<div class="row">
<div class="col-md-4">
<h3>Ingredients</h3>
<div id="ingredients">
<%= f.simple_fields_for :ingredients do |ingredient| %>
<%= render "ingredients_fields", f: ingredient %>
<div class="links">
<%= link_to_add_association "Add Ingredient", f, :ingredients, class: "btn btn-default add-button" %>
</div>
<% end %>
</div>
</div>
<div class="col-md-4">
<h3>Directions</h3>
<div id="directions">
<%= f.simple_fields_for :directions do |direction| %>
<%= render "directions_fields", f: direction %>
<div class="links">
<%= link_to_add_association "Add Step", f, :directions, class: "btn btn-default add-button" %>
</div>
<% end %>
</div>
</div>
<div class="col-md-4">
<h3>Utensils</h3>
<div id="utensils">
<%= f.simple_fields_for :utensils do |utensil| %>
<%= render "utensils_fields", f: utensil %>
<div class="links">
<%= link_to_add_association "Add Utensil", f, :utensils, class: "btn btn-default add-button" %>
</div>
<% end %>
</div>
</div>
</div>
<%= f.button :submit, class: "btn btn-primary" %>
</div>
部分(针对路线)
<div class="form-inline.clearfix">
<div class="nested-fields">
<%= f.input :step, input_html: { class: "form-input form-control" } %>
<%= link_to_remove_association "Remove", f, class: "form-button btn btn-default" %>
</div>
</div>
器具的轮廓也没有出现,我不知道为什么。
这就是它的样子:nested forms not showing
任何帮助将不胜感激,谢谢!
答案 0 :(得分:0)
是否有任何嵌套项目?
因为如果没有它会解释行为:你的link_to_add_association
在simple_fields_for
循环内部,因此它将显示每个嵌套项目,但如果有,它也将永远不会显示没有(注意:这可能是期望的行为,但我猜大多数情况下不是这样)。
cocoon文档中的所有示例都将link_to_add_association
置于simple_fields_for
循环之外。如果您在阅读haml时遇到问题,请查看ERB examples。