2015-04-05 66 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语句

,但我怎么可以在这里创建多个数量?