Ruby on rails Rails:通过关联和用于创建新实例的表单来实现
我还是Rails的新手,只是想通过协会建立我的第一个 食谱有很多成分,每种成分都有一个配方所需的量。配料量表包含配方id、配料id和用量 创建新配方时,我希望能够在同一位置创建这些配方/成分关联。最后,我将为配料构建一个AJAX自动完成程序。现在,作为一个小步骤,我只想假设成分存在,并在我把这部分拿下来后检查一下 那么,我如何才能为菜谱创建new.html.erb来执行此操作?我如何扩展一种以上的成分的形式 现在的情况是,在经历了 我仍然无法获得任何字段来添加成分。当前代码如下Ruby on rails Rails:通过关联和用于创建新实例的表单来实现,ruby-on-rails,Ruby On Rails,我还是Rails的新手,只是想通过协会建立我的第一个 食谱有很多成分,每种成分都有一个配方所需的量。配料量表包含配方id、配料id和用量 创建新配方时,我希望能够在同一位置创建这些配方/成分关联。最后,我将为配料构建一个AJAX自动完成程序。现在,作为一个小步骤,我只想假设成分存在,并在我把这部分拿下来后检查一下 那么,我如何才能为菜谱创建new.html.erb来执行此操作?我如何扩展一种以上的成分的形式 现在的情况是,在经历了 我仍然无法获得任何字段来添加成分。当前代码如下 class Re
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
def new
@recipe = Recipe.find(params[:recipe_id])
@ingredient = Ingredient.find(params[:ingredient_id])
@ingredient_amount = Recipe.ingredient_amounts.build
end