ruby-on-rails - Rails has_many,:通过表格将变量添加到连接表
问题描述
我正在尝试构建一个用于存储食谱的应用程序,以便我可以(最终)根据食谱成分构建购物清单。
我正在苦苦挣扎的是能够将成分与基于它们的食谱联系起来measures
,即一个食谱可以使用300 克面粉和一撮盐,而另一个食谱可能使用两杯面粉和一茶匙盐。
我已经用三个表设置了数据库Recipes
:Measures
和Ingredients
。但是,我在尝试创建基本表单元素时遇到了困难,这样我就可以将unit
(例如克、杯或毫升)和数量(1 或 500)与度量的成分相关联。那么,我如何将表格放在一起以允许这样做?
我通过为所有可用成分添加一组复选框来开始表单,但这仅允许链接或不链接成分 - 我不知道还添加有关要在此处添加的连接表的元素的信息.
这是recipes_controller:
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 %>
谢谢你的帮助!
解决方案
推荐阅读
- spring - 实现 PUT 后不支持请求方法“GET”
- c++ - 使用 opencv 库从摄像头捕获需要太多功率
- asp.net-core - NET Core 中的观察者模式
- node.js - Bootstrap 项目的一致构建过程
- html - 防止“此时无法进入中断模式”错误消息?
- .htaccess - 防止直接文件访问
- r - R 中带有 gam 的函数图中的错误 - 负二项式预测
- oracle - AVG 两个日期,NULL 值问题
- java - org.openqa.selenium.SessionNotCreatedException:尝试使用 Selenium v3.8.1 启动 Firefox 时找不到匹配的功能集
- python - Python在一个类中创建未知数量的属性