2015-04-05 78 views
0

我與嵌套形式鬥爭。 有是三類配方,數量和成分:4.2沒有繭,簡單的形式或formtastic?嵌套形式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 

信息查看配方#新

<%= 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 

任何想法?謝謝!

回答

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

解決的select語句

,但我怎麼可以在這裏創建多個數量?