0

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 つの質問:

  1. 私の .each ブロックは関連付けに対して正しく見えますか?

  2. フォームヘルパーが新しい行を認識して適切なデータベース挿入を作成するように、そのテーブルのクライアント側に新しい行を追加する最良の方法は何ですか? このようなオブジェクトの配列を作成するという点で、Rails マジックがどのように機能するかについては、よくわかりません。

4

1 に答える 1

1

Ryan Bateのnested_formが進むべき道のようで、simple_formもサポートしています。

基本的な使用法:

<%= simple_nested_form_for @recipe do |f| %>

次に、[新しい材料を追加]リンクを表示する場所:

<%= f.link_to_add "Add new ingredient", :recipe_ingredients %>

宝石自体には優れたドキュメントがあります。Wikiページも確認してください。

于 2013-03-01T05:37:43.133 に答える