【发布时间】:2015-06-17 14:59:23
【问题描述】:
我正在尝试创建食谱应用。在我的应用程序中,我有表成分(名称),表食谱(类型_of,代码,描述)连接表数量(recipe_id,成分_id,数量)
我希望能够在创建时将配料添加到我的食谱中。食谱可以有很多成分。
我的模型:
class Ingredient < ActiveRecord::Base
has_many :quantities
has_many :recipes, through: :quantities
has_many :stock_of_ingredients
end
class Quantity < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
accepts_nested_attributes_for :ingredient,
:reject_if => :all_blank
end
class Recipe < ActiveRecord::Base
has_many :quantities
has_many :ingredients, :through => :quantities
accepts_nested_attributes_for :quantities,
:reject_if => :all_blank,
:allow_destroy => true
accepts_nested_attributes_for :ingredients
end
我的 Recipe 控制器是从脚手架创建的
def create
@recipe = Recipe.new(recipe_params)
respond_to do |format|
if @recipe.save
format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
format.json { render :show, status: :created, location: @recipe }
else
format.html { render :new }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end end
我也加了
def recipe_params
params.require(:recipe).permit(:type_of_base, :code, :description, :quantities_attributes =>[:quantity, :recipe_id, :ingredient_id, :ingredient_attributes])
end
我不知道我需要从基本控制器创建的数量控制器吗?
现在我的表单是这样的
<%= form_for(@recipe, html: { class: "form-horizontal", role: "form" }) do |f| %>
...
<div class="form-group">
...
</div>
<div class="ingderdient-wraper">
<%= render "quantites/quantity_fields" %>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<%= f.submit class: "btn btn-primary" %>
</div>
</div>
<% end %>
还有我的渲染文件
<%= text_field :quantity %>
<%= select :ingredient_ids, Ingredient.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %>
但这也不能正常工作,我希望有可能添加更多的成分。需要一个按钮添加更多。
如果有人可以向我解释如何直截了当。问候
【问题讨论】:
-
不能正常工作是什么意思?
-
不将数据保存到数量表中。
-
请发布您的日志。
-
谢谢,现在我的参数数量错误(1 代表 2..3)
标签: ruby-on-rails ruby associations