4.2 没有茧,简单的形式还是形式多样?嵌套表格食谱

4.2 Without cocoon, simple form or formtastic? Nested forms cookbook

我在使用嵌套表单时遇到了困难。 共有三个 类 配方、数量和成分:

class Recipe < ActiveRecord::Base
  belongs_to :user
  has_many :quantities
  has_many :ingredients, through: :quantities
  accepts_nested_attributes_for :quantities

class Quantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
  accepts_nested_attributes_for :ingredient, :reject_if => :all_blank

class Ingredient < ActiveRecord::Base
  has_many :quantities
  has_many :recipes, :through => :quantities

配方控制器

def new
  @recipe = current_user.recipes.build
  @quantity = @recipe.quantities.build
end
def create
    @recipe = current_user.recipes.build(recipe_params)
    if @recipe.save
      redirect_to @recipe
    else
      render 'new'
    end
end
  private
    def recipe_params
      params.require(:recipe).permit(
        :name, 
        quantities_attributes: [:id, :amount, :ingredient_id],
      )
end

查看食谱#new

<%= form_for @recipe, html: {class: "form-horizontal"} do |f| %>
  <li class="control-group">
   <%= f.label :name, "Recipe Name", class: "control-label" %>
   <div class="controls"><%= f.text_field :name %></div>
  </li>
  <%= f.fields_for :quantities do |quantity| %>
    <%= render 'quantity_fields', f: quantity %>
  <% end %>
  <%= f.submit %>
<% end %>

_quantity_fields

<%= f.label :amount, "Amount:" %>
<%= f.text_field :amount %>

此处应遵循包含 Ingredient 内容的 Select 输入,POST 请求应在 Quantity 列中插入 ingredient_id。

<%= f.select("ingredient_id", "ingredient_id", Ingredient.all.collect
  {|p| [ p.name, p.id ] }, {include_blank: 'Choose'}) %>

获得

NoMethodError in Recipes#new

Showing C:/Sites/4.2/sample_app - Kopie/app/views/recipes/_quantity_fields.html.erb 
where line #6 raised:

undefined method `merge' for [["Sugar", 1], ["Butter", 2]]:Array

有什么想法吗?谢谢!

<%= f.collection_select(:ingredient_id, Ingredient.all, :id, :name) %>

解决了 select 语句

但是如何在这里创建多个数量?