我仍然是Rails的新手,只是试图通过关联设置获得我的第一个has_many。
食谱有许多成分,每种成分都含有配方所需的量。 ingredient_amount表有recipe_id,ingredient_id和amount。
创建新配方时,我希望能够在同一个地方创建这些配方/配料关联。最后,我将为这些成分构建一个AJAX自动完成器。现在,作为一个婴儿步骤,我想假设成分存在,并在我将这部分放下后进行检查。
那么,我如何为配方制作new.html.erb呢?如何扩展多种成分的表格?
现在看来,经过http://weblog.rubyonrails.org/2009/1/26/nested-model-forms之后 我仍然无法获得添加成分的任何领域。目前的代码如下。
class Recipe < ActiveRecord::Base
has_many :ingredient_amounts
has_many :ingredients, :through => :ingredient_amounts
accepts_nested_attributes_for :ingredient_amounts, :allow_destroy => true
end
class IngredientAmount < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
end
class Ingredient < ActiveRecord::Base
has_many :ingredient_amounts
has_many :recipes :through => :ingredient_amounts
end
这是我现在拥有的new.html.erb:
<h1>New recipe</h1>
<% form_for @recipe do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :instructions %><br />
<%= f.text_area :instructions %>
</p>
<p>
<%= f.label :numberOfServings %><br />
<%= f.text_field :numberOfServings %>
</p>
<p>
<%= f.label :prepTime %><br />
<%= f.text_field :prepTime %>
</p>
<p>
<% f.fields_for :ingredient_amounts do |ingredient_form| %>
<%= ingredient_form.label :ingredient_formedient_id, 'Ingredient' %>
<%= ingredient_form.collection_select :ingredient_id, Ingredient.all, :id, :name, :prompt => "Select an Ingredient"%>
<%= ingredient_form.text_field :amount %>
<% unless ingredient_form.object.new_record? %>
<%= ingredient_form.label :_delete, 'Remove:' %>
<%= ingredient_form.check_box :_delete %>
<% end %>
</p>
<% end %>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', recipes_path %>
配方控制器的重要部分:
def new
@recipe = Recipe.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @recipe }
end
end
def create
@recipe = Recipe.new(params[:recipe])
respond_to do |format|
if @recipe.save
flash[:notice] = 'Recipe was successfully created.'
format.html { redirect_to(@recipe) }
format.xml { render :xml => @recipe, :status => :created, :location => @recipe }
else
format.html { render :action => "new" }
format.xml { render :xml => @recipe.errors, :status => :unprocessable_entity }
end
end
end
而且......我不知道从哪里开始在ingredient_amounts控制器中。 这是我第一次尝试,我很确定它不是那么接近:)。
def new
@recipe = Recipe.find(params[:recipe_id])
@ingredient = Ingredient.find(params[:ingredient_id])
@ingredient_amount = Recipe.ingredient_amounts.build
end
感谢您的帮助!
答案 0 :(得分:1)
我相信你要找的是'嵌套模型表'。
试试此链接:http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
当您不熟悉术语时,很难知道要搜索的内容:)