Ruby on rails Rails有很多:通过表单将变量添加到联接表中
我正在尝试构建一个存储食谱的应用程序,这样我就可以(最终)根据食谱成分建立购物清单 我正在努力的是能够根据配料的Ruby on rails Rails有很多:通过表单将变量添加到联接表中,ruby-on-rails,forms,join,nested-forms,has-many-through,Ruby On Rails,Forms,Join,Nested Forms,Has Many Through,我正在尝试构建一个存储食谱的应用程序,这样我就可以(最终)根据食谱成分建立购物清单 我正在努力的是能够根据配料的测量方法将配料与配方联系起来,即一份配方可能需要300克面粉和一小撮盐,而另一份配方可能需要两杯面粉和一茶匙盐 我用三个表设置了数据库:配方、度量和成分。但是,我一直在尝试创建基本的表单元素,以便将单位(例如克、杯或毫升)和数量(1或500)与度量值的成分相关联。那么,我如何将表单组合在一起以允许这样做呢 我在表单开始时为所有可用的成分添加了一组复选框,但这只允许链接或不链接成分-我知
测量方法将配料与配方联系起来,即一份配方可能需要300克面粉和一小撮盐,而另一份配方可能需要两杯面粉和一茶匙盐
我用三个表设置了数据库:配方
、度量
和成分
。但是,我一直在尝试创建基本的表单元素,以便将单位
(例如克、杯或毫升)和数量(1或500)与度量值的成分相关联。那么,我如何将表单组合在一起以允许这样做呢
我在表单开始时为所有可用的成分添加了一组复选框,但这只允许链接或不链接成分-我知道没有办法在这里添加关于要添加的连接表元素的信息
以下是配方控制器:
def new
@recipe = Recipe.new
@ingredients = Ingredient.all
end
def edit
@recipe = Recipe.find(params[:id])
@ingredients = Ingredient.all
end
def create
@recipe = Recipe.new(recipe_params)
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
...
private
def recipe_params
params.require(:recipe).permit(:name, :method, :category, ingredient_ids:[])
end
模型:
class Recipe < ApplicationRecord
has_many :measures
has_many :ingredients, through: :measures
accepts_nested_attributes_for :ingredients
end
class Measure < ApplicationRecord
belongs_to :ingredient
belongs_to :recipe
accepts_nested_attributes_for :ingredient
end
class Ingredient < ApplicationRecord
has_many :measures
has_many :recipes, through: :measures
end
类配方
基本配方形式部分:
# /views/recipes/_form.html.erb
<%= form_for(@recipe) do |form| %>
<p>
<%= form.label :name %><br>
<%= form.text_field :name %>
</p>
<p>
<%= form.collection_check_boxes :ingredient_ids, @ingredients, :id, :name %>
</p>
<p>
<%= form.fields_for :measures do |ff| %>
<% @ingredients.each do |ingredient| %>
<%= ff.label :unit %>
<%= ff.text_field :unit %> |
<%= ff.label :quantity %>
<%= ff.text_field :quantity %> |
<%= ff.label ingredient.name %>
<%= ff.check_box :ingredient_id %>
<br>
<% end %>
<% end %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
#/views/recipes/_form.html.erb
|
|
谢谢你的帮助