我正在使用' nested_form_fields' gem来构建Rails表单。它确实有效但不是以正确的方式。
单击删除按钮时,一次删除所有字段。 (当我添加三个text_fields并尝试删除其中一个时,所有字段都会立即删除,并且没有输入任何内容的新text_field。)
如何更改它,仅删除单击删除按钮的特定字段,而其他字段只保留?
_form.html.erb
<div class="form-horizontal">
<%= form_for(recipe) do |f| %>
<div class="form-group">
<%= f.label :name, 'Title' %>
<%= f.text_area :title, class: 'form-control', placeholder:'Enter Recipe Title' %>
<%= f.label :name, 'Comment' %>
<%= f.text_area :content, class: 'form-control', placeholder: 'about the Recipe' %>
<%= f.label :name, 'Volume' %>
<%= f.number_field :volume, class: 'form-control', placeholder: 'Enter integer number of volume' %>
</div>
<div class="form-group">
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr>
<th>Ingredient</th>
<th>amount</th>
</tr>
<%= f.nested_fields_for :ingredients, wrapper_tag: :tr do |q| %>
<div>
<td><%= q.text_field :name, class: 'form-control', placeholder:'Enter Ingredient name' %></td>
<td><%= q.text_field :amount, class: 'form-control', placeholder:'Enter amount' %></td>
</div>
<td class="col-xs-1">
<button type="button" class="close form-control" aria-label="Close"><%= q.remove_nested_fields_link %></button>
</td>
<% end %>
</tbody>
</table>
<%= f.add_nested_fields_link :ingredients, 'Add field', class: 'btn', role: 'button' %>
</div>
<div class="form-group">
<table class="table table-striped table-bordered table-hover">
<tbody>
<tr>
<th>Instractions</th>
</tr>
<%= f.nested_fields_for :instractions, wrapper_tag: :tr, class: ' fields row' do |q| %>
<td class="col-xs-11">
<%= q.text_field :content, class: 'form-control', placeholder:'Enter Instraction' %>
</td>
<td class="col-xs-1">
<button type="button" class="close form-control" aria-label="Close"><%= q.remove_nested_fields_link %></button>
</td>
<% end %>
</tbody>
</table>
<%= f.add_nested_fields_link :instractions, 'Add field', class: 'btn', role: 'button' %>
</div>
<%= f.submit 'Post', class: 'btn' %>
<% end %>
</div>
模型
class Recipe < ApplicationRecord
belongs_to :user
has_many :ingredients, dependent: :destroy
has_many :instractions, dependent: :destroy
accepts_nested_attributes_for :ingredients, allow_destroy: true
accepts_nested_attributes_for :instractions, allow_destroy: true
end
class Instraction < ApplicationRecord
belongs_to :recipe
end
class Ingredient < ApplicationRecord
belongs_to :recipe
end
控制器
class RecipesController < ApplicationController
def new
@recipe = current_user.recipes.build
@recipe.ingredients.build
@recipe.instractions.build
end
def create
@recipe = current_user.recipes.build(recipe_params)
if @recipe.save
flash[:success] = 'Recipe Posted'
redirect_to current_user
else
flash[:danger] = 'Sorry, Failed to post.'
render :new
end
end
end