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 %>
2 つの質問:
私の .each ブロックは関連付けに対して正しく見えますか?
フォームヘルパーが新しい行を認識して適切なデータベース挿入を作成するように、そのテーブルのクライアント側に新しい行を追加する最良の方法は何ですか? このようなオブジェクトの配列を作成するという点で、Rails マジックがどのように機能するかについては、よくわかりません。