【发布时间】:2013-02-27 17:26:46
【问题描述】:
我正在 Rails 中构建一个食物食谱数据库,并且我正在尝试构建一个方便的表单来使用 Jquery 添加成分。
我的联想:
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, :through => :recipe_ingredients
accepts_nested_attributes_for :recipe_ingredients
end
class Ingredient < ActiveRecord::Base
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
我的食谱表格如下所示(简化):
<%= simple_form_form(@recipe) do |f| %>
<div class="form-inputs">
<%= f.input :name %>
<fieldset><legend>Ingredients</legend>
<table class="table">
<% @recipe.recipe_ingredients.each do |recipe_ingredient| %>
<tr>
<%= f.fields_for :recipe_ingredients, recipe_ingredient do |dif| %>
<td><%= dif.text_field :ingredient %></td>
<td><%= dif.text_field :amount %></td>
<% end %>
</tr>
<% end %>
</table>
<div class="btn-group">
<a href="#" class="btn btn-primary">Add New Ingredient</a>
</div>
</fieldset>
</div>
<% end %>
两个问题:
我的 .each 块对于关联看起来是否正确?
向该表客户端添加新行以便表单助手识别新行并创建适当的数据库插入的最佳方法是什么?我不太清楚 Rails 魔术在创建这样的对象数组方面是如何工作的。
【问题讨论】:
-
您想在创建食谱时创建配料还是将现有配料添加到食谱中?
-
@SybariteManoj 你是对的,它有很大的不同。至于问题#2,只是一个提示:nested attributes
-
@m_x 是的,如果他想添加新成分,那么可以使用 nested_attributes,但在这种情况下,不需要
many-many关联,因为总是会创建成分。但是如果他想添加现有的成分,那么可以使用ingredient_ids。在最后一种情况下,当他想要两者时,他可能需要结合使用以前的方法。 :) -
我不想创建新成分,但我确实想使用 recipe_ingredients 连接表将现有成分分配给配方。我没有提到我的 Recipe 模型有一个 accept_nested_attributes_for 调用。将其添加到我原来的问题中。
-
我应该补充一点,我非常了解关联是如何工作的,而且我大约 99% 确信我已经正确设置了这些。我还没有掌握的是如何设置一个表格来反映这些关联。通常我会在表单字段名称中创建一个数组并在控制器中执行对象构建逻辑,但如果我正确设置表单字段,Rails 可能已经涵盖了这一点。
标签: ruby-on-rails forms associations