【发布时间】:2018-05-21 13:50:12
【问题描述】:
我正在尝试在食谱的编辑/创建部分中为配料、说明和用具创建嵌套字段,但只显示字段的轮廓,没有任何嵌套位。
模型
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>
餐具的轮廓也没有出现,我不知道为什么。
任何帮助将不胜感激,谢谢!
【问题讨论】:
-
cocoon gem 需要正确的 html 格式才能工作,我认为你的 html 正在制造问题,尝试注释 row 和 col 代码并以简单格式运行
-
我将列和行注释掉了,但似乎没有什么区别,盒子里什么都没有显示,而且餐具盒也不在那里。
-
你是在
@recipe.ingredients.build这样的控制器方法中建立你的关联吗?我认为这个问题与你的HTML结构有关,首先尝试用简单的UI来实现它,而不使用引导程序
标签: ruby-on-rails simple-form cocoon-gem